feat(web): a switch in Settings for starting Discover from your listening

Turning it on shows a dialog that says the names of the most played artists go to Last.fm. Turning it off asks nothing, and a failed change leaves the switch as it was.
This commit is contained in:
tgiachi 2026-11-12 14:05:49 +01:00
commit 3cd0ef7150
6 changed files with 200 additions and 5 deletions

View file

@ -0,0 +1,80 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, waitFor } 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 ListeningSwitch from './ListeningSwitch'
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
})
function setup(initial: boolean, over: MockRoutes = {}) {
let on = initial
const mocked = mockFetch({
'GET /api/v1/me/settings': () => ({ discover_from_listening: on }),
'PATCH /api/v1/me/settings': ({ init }) => {
on = JSON.parse(String(init.body)).discover_from_listening
return { discover_from_listening: on }
},
...over,
})
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
render(
<QueryClientProvider client={client}>
<ListeningSwitch />
</QueryClientProvider>,
)
return mocked
}
const toggle = () => screen.findByRole('switch', { name: 'Start Discover from my listening' })
const patches = (calls: { key: string }[]) => calls.filter((c) => c.key === 'PATCH /api/v1/me/settings')
test('it says what turning it on sends, before anything is asked', async () => {
setup(false)
expect(await toggle()).toHaveAttribute('aria-checked', 'false')
expect(screen.getByText(/names of the artists you play most go to Last\.fm/i)).toBeInTheDocument()
})
test('turning it on asks first and sends nothing until the answer is yes', async () => {
const { calls } = setup(false)
await userEvent.click(await toggle())
const dialog = await screen.findByRole('dialog')
expect(dialog).toHaveTextContent(/Last\.fm/)
expect(patches(calls)).toHaveLength(0)
await userEvent.click(screen.getByRole('button', { name: 'Turn on' }))
await waitFor(() => expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'true'))
expect(patches(calls)).toHaveLength(1)
expect(JSON.parse(String(patches(calls)[0].init.body))).toEqual({ discover_from_listening: true })
})
test('cancelling leaves it off and sends nothing', async () => {
const { calls } = setup(false)
await userEvent.click(await toggle())
await userEvent.click(await screen.findByRole('button', { name: 'Cancel' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'false')
expect(patches(calls)).toHaveLength(0)
})
test('turning it off needs no question', async () => {
const { calls } = setup(true)
const sw = await toggle()
await waitFor(() => expect(sw).toHaveAttribute('aria-checked', 'true'))
await userEvent.click(sw)
await waitFor(() => expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'false'))
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(JSON.parse(String(patches(calls)[0].init.body))).toEqual({ discover_from_listening: false })
})
test('a failure is shown and the switch stays as it was', async () => {
setup(false, { 'PATCH /api/v1/me/settings': () => apiError(500, 'internal') })
await userEvent.click(await toggle())
await userEvent.click(await screen.findByRole('button', { name: 'Turn on' }))
expect(await screen.findByRole('alert')).toBeInTheDocument()
expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'false')
})

View file

@ -0,0 +1,76 @@
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ApiError } from '@/api/client'
import { useMySettings, useUpdateSettings } from '@/api/discover'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { errorMessageKey } from '@/i18n'
import { cn } from '@/lib/utils'
/**
* Whether Discover may start from the artists you play most. Turning it on sends their names to Last.fm
* (when an admin turned Last.fm on), so it asks first and says so; turning it off asks nothing.
*/
export default function ListeningSwitch() {
const { t } = useTranslation()
const settings = useMySettings()
const update = useUpdateSettings()
const [asking, setAsking] = useState(false)
const on = settings.data?.discover_from_listening === true
function change(value: boolean) {
setAsking(false)
update.mutate({ discover_from_listening: value })
}
return (
<div className="flex max-w-xl flex-col gap-3">
<div className="flex items-center gap-4">
<button
type="button"
role="switch"
aria-checked={on}
aria-labelledby="listening-label"
disabled={settings.data === undefined || update.isPending}
onClick={() => (on ? change(false) : setAsking(true))}
className={cn(
'relative h-7 w-12 shrink-0 rounded-md border border-input transition-colors disabled:opacity-50',
on ? 'bg-primary' : 'bg-secondary',
)}
>
<span
aria-hidden="true"
className={cn(
'absolute top-0.5 left-0.5 size-5 rounded-sm bg-background transition-transform motion-reduce:transition-none',
on && 'translate-x-5',
)}
/>
</button>
<span id="listening-label" className="font-semibold">
{t('discover.listening.label')}
</span>
</div>
<p className="text-sm text-muted-foreground">{t('discover.listening.help')}</p>
{update.isError && (
<p role="alert" className="text-sm text-destructive">
{t(errorMessageKey(update.error instanceof ApiError ? update.error.code : 'unknown'))}
</p>
)}
<Dialog open={asking} onOpenChange={setAsking}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('discover.listening.confirmTitle')}</DialogTitle>
<DialogDescription>{t('discover.listening.confirmBody')}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setAsking(false)}>
{t('discover.listening.cancel')}
</Button>
<Button onClick={() => change(true)}>{t('discover.listening.turnOn')}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}

View file

@ -58,6 +58,17 @@
"currentPasswordWrong": "The current password is wrong.",
"changePassword": "Change password"
},
"discover": {
"title": "Discover",
"listening": {
"label": "Start Discover from my listening",
"help": "When this is on, the names of the artists you play most go to Last.fm, if an admin turned Last.fm on, to find similar artists. When it is off, Discover starts only from artists you pick.",
"confirmTitle": "Send your top artists to Last.fm?",
"confirmBody": "Discover will send the names of the artists you play most to Last.fm, if an admin turned Last.fm on, and ask for similar artists. Nothing else about you is sent. You can turn this off at any time.",
"turnOn": "Turn on",
"cancel": "Cancel"
}
},
"home": {
"greeting_morning": "Good morning",
"greeting_afternoon": "Good afternoon",

View file

@ -58,6 +58,17 @@
"currentPasswordWrong": "La password attuale è sbagliata.",
"changePassword": "Cambia password"
},
"discover": {
"title": "Discover",
"listening": {
"label": "Avvia Discover dai miei ascolti",
"help": "Se è acceso, i nomi degli artisti che ascolti di più vanno a Last.fm, se un admin l'ha acceso, per trovare artisti simili. Se è spento, Discover parte solo dagli artisti che scegli tu.",
"confirmTitle": "Mandare i tuoi artisti preferiti a Last.fm?",
"confirmBody": "Discover manderà a Last.fm i nomi degli artisti che ascolti di più, se un admin ha acceso Last.fm, e chiederà artisti simili. Non viene mandato nient'altro su di te. Puoi spegnerlo quando vuoi.",
"turnOn": "Accendi",
"cancel": "Annulla"
}
},
"home": {
"greeting_morning": "Buongiorno",
"greeting_afternoon": "Buon pomeriggio",

View file

@ -1,3 +1,4 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
@ -12,14 +13,18 @@ import SettingsPage from './SettingsPage'
const noContent = () => new Response(null, { status: 204 })
function renderSettings() {
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
return render(
<MemoryRouter>
<SettingsPage />
</MemoryRouter>,
<QueryClientProvider client={client}>
<MemoryRouter>
<SettingsPage />
</MemoryRouter>
</QueryClientProvider>,
)
}
beforeEach(async () => {
mockFetch({ 'GET /api/v1/me/settings': () => ({ discover_from_listening: false }) })
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
initTheme()
@ -93,12 +98,19 @@ test('choosing Italian changes the words on the page', async () => {
expect(localStorage.getItem('sonda.lang')).toBe('it')
})
test('Discover has its own group with the switch for using your listening, off until you turn it on', async () => {
renderSettings()
expect(screen.getByRole('region', { name: 'Discover' })).toBeInTheDocument()
const sw = await screen.findByRole('switch', { name: 'Start Discover from my listening' })
expect(sw).toHaveAttribute('aria-checked', 'false')
})
test('a new password of seven characters is refused here, with no request', async () => {
const { calls } = mockFetch({})
renderSettings()
await changePassword('old-password', '1234567')
expect(await screen.findByRole('alert')).toHaveTextContent('The new password needs 8 to 256 characters.')
expect(calls).toHaveLength(0)
expect(calls.filter((c) => c.url.pathname === '/api/v1/auth/password')).toHaveLength(0)
})
test('a new password longer than 256 bytes is refused here, with no request', async () => {
@ -109,7 +121,7 @@ test('a new password longer than 256 bytes is refused here, with no request', as
await userEvent.paste('x'.repeat(257))
await userEvent.click(screen.getByRole('button', { name: 'Change password' }))
expect(await screen.findByRole('alert')).toHaveTextContent('8 to 256')
expect(calls).toHaveLength(0)
expect(calls.filter((c) => c.url.pathname === '/api/v1/auth/password')).toHaveLength(0)
})
test('a changed password signs this session out, because the server ends every session', async () => {

View file

@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next'
import { api, ApiError } from '@/api/client'
import { logout, useSession } from '@/auth/session'
import ChoiceGroup from '@/components/ChoiceGroup'
import ListeningSwitch from '@/components/ListeningSwitch'
import Section from '@/components/Section'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@ -136,6 +137,10 @@ export default function SettingsPage() {
/>
</Section>
<Section title={t('discover.title')}>
<ListeningSwitch />
</Section>
<Section title={t('settings.password')}>
<ChangePassword />
</Section>