Música se ordena: pestañas, buscador, y listas de diez con "Mostrar más"
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s

La pantalla era una sola columna —radio, después podcasts, después listas— y tres
listas de veinte filas es una pantalla por la que se baja buscando lo que ya sabías
que querías. Ahora pregunta primero: **Radio | Podcasts | Listas**, una lista a la
vez, **diez filas** y un **"Mostrar más"** que dice cuántas esconde. Nada queda fuera
de alcance y nada más está en pantalla mientras decidís: el subtítulo también dice qué
estás mirando en vez de hablar siempre de listas.

El **buscador** busca lo que tengas abierto y en el origen, no en la página: `jazz`
le pregunta al directorio de emisoras y `crimen` al de podcasts de Apple —filtrado,
como siempre, a español, y pasando por **la misma** función de filtro que una
categoría, porque un segundo camino más barato al catálogo es como se pierde una
regla—. Con menos de dos letras no se busca ni se pide nada: una letra coincide con
todo y sería una petición por tecla para una respuesta inservible.

La búsqueda de emisoras **ordena por lo que se buscó**: el directorio coincide con
subcadenas en cualquier parte, así que *techno* devolvía "# TOP 100 CLUB CHARTS -
DANCE & DJ MIX RADIO" —real, con "techno" entre sus etiquetas— por delante de toda
emisora llamada Techno Algo. El nombre pesa antes que la popularidad y a igual peso
gana el nombre más corto; los canales de SomaFM y los mixes de Paradise que coinciden
van primero, porque no tienen publicidad y su stream ya se sabe que funciona. La
búsqueda del directorio va con `is_https=true`, cacheada por consulta.

`lib/paging.js` es puro y tiene test porque tiene un borde fácil de equivocar en un
componente: una lista que se encoge —una búsqueda nueva, una emisora desmarcada— no
puede dejar el tamaño de página pasado del final, que se ve como "Mostrar más" que no
hace nada.

Verificado contra los directorios reales: `radio?q=jazz` → Sonic Universe (SomaFM) y
después Jazz 24; `radio?q=miami` → Miami Beach Radio, 105 Miami; `podcasts?q=crimen`
→ 20 programas en español (es, es-ar) y `q=entrenamiento en casa` → 3; `?q=j` no
busca. `relevance` y `rankStations` se comprobaron por mutación: sacar el orden hace
fallar el test que lo mira de punta a punta.
This commit is contained in:
dsantillan committed 2026-09-23 21:24:50 -04:00
1 parent 22654c61fc
commit d5cf0d8d64
16 files changed
+845 -81

No files matched your search

+4
View File
@@ -1135,6 +1135,10 @@ body.chips-dragging *{cursor:inherit}
.mus-rad-go{font-size:17px;color:var(--acc);flex:0 0 auto}
.mus-rad-save{color:var(--label-3)}
.mus-rad-save .icn{font-size:17px}
/* The screen's three lists, one at a time. The segmented control sits right under the search box and
above everything it switches between, so the screen reads top to bottom: what am I looking at,
which of the three, and then the list. */
.mus-tabs{margin:2px 0 12px}
.mus-sub-h{font-size:12px;font-weight:600;color:var(--label-3);text-transform:uppercase;letter-spacing:.04em;margin:2px 2px 6px}
/* The episodes sheet: a show's feed, newest first. Rows are buttons because the whole row plays the
+29
View File
@@ -0,0 +1,29 @@
/* Showing ten of something instead of forty.
*
* The Música screen carries three lists — stations, podcasts, playlists — and a list that renders
* everything is a screen you scroll through looking for the thing you already know you want. Ten
* rows and a "show more" is the house style here (the exercise library and the admin activity log
* both work this way), and it is the reason the screen reads as three small lists rather than one
* long one.
*
* Pure and tested because the arithmetic has an edge that is easy to get wrong in a component: a
* list that *shrinks* — a new search, a station unstarred — must not leave the page size past its
* end, which reads as "show more" doing nothing. */
export const PAGE = 10
/** The first `shown` items. Never more than there are, and never a crash on a missing list. */
export const visible = (list, shown) => (Array.isArray(list) ? list : []).slice(0, Math.max(0, shown))
/** Whether there is anything left to reveal. */
export const hasMore = (list, shown) => (Array.isArray(list) ? list.length : 0) > Math.max(0, shown)
/**
* How many to show after "show more".
*
* Clamped to the list: the button is only ever pressed against a list that shrank since it was
* drawn, and growing past the end would leave it on screen doing nothing at all.
*/
export const nextShown = (shown, total, step = PAGE) => Math.min((Number(shown) || 0) + step, Math.max(0, Number(total) || 0))
/** How many are hidden — for a button that says how much it is hiding, or nothing at all. */
export const hiddenCount = (list, shown) => Math.max(0, (Array.isArray(list) ? list.length : 0) - Math.max(0, shown))
+46
View File
@@ -0,0 +1,46 @@
/* Ten at a time, and the edges of that. */
import { describe, expect, it } from 'vitest'
import { PAGE, visible, hasMore, nextShown, hiddenCount } from './paging.js'
const list = n => Array.from({ length: n }, (_, i) => i)
describe('showing a list in pages of ten', () => {
it('shows ten, not everything', () => {
expect(PAGE).toBe(10)
expect(visible(list(40), PAGE)).toHaveLength(10)
expect(visible(list(40), PAGE)[9]).toBe(9)
})
it('shows what there is when there is less than a page', () => {
expect(visible(list(4), PAGE)).toEqual([0, 1, 2, 3])
expect(hasMore(list(4), PAGE)).toBe(false)
})
it('says when there is more, and stops saying it at the end', () => {
expect(hasMore(list(11), PAGE)).toBe(true)
expect(hasMore(list(20), 20)).toBe(false)
// The bug this exists for: a list that shrank under a page size that was already past its end.
expect(hasMore([], PAGE)).toBe(false)
expect(hasMore(list(3), 10)).toBe(false)
})
it('grows by a page, and never past the end', () => {
expect(nextShown(PAGE, 40)).toBe(20)
expect(nextShown(30, 40)).toBe(40)
// "Show more" on a list that shrank to eight would otherwise leave the button there forever.
expect(nextShown(20, 8)).toBe(8)
})
it('counts what it is hiding', () => {
expect(hiddenCount(list(25), PAGE)).toBe(15)
expect(hiddenCount(list(3), PAGE)).toBe(0)
})
it('survives a list that is not there yet', () => {
expect(visible(null, PAGE)).toEqual([])
expect(visible(undefined, PAGE)).toEqual([])
expect(hasMore(null, PAGE)).toBe(false)
expect(hiddenCount(null, PAGE)).toBe(0)
expect(visible(list(5), null)).toEqual([])
})
})
+9
View File
@@ -1409,6 +1409,15 @@ export default {
'The server is running an older API than this screen: the numbers may not match Apple Health, and the hourly detail and the sync receipt will not appear until the api container is updated.': 'El servidor está corriendo una api más vieja que esta pantalla: los números pueden no coincidir con Apple Health, y el detalle por hora y el recibo del último envío no van a aparecer hasta que se actualice el contenedor de la api.',
'using {0}': 'se usa {0}',
// podcasts
'Live radio, nothing downloaded': 'Radio en vivo, sin descargar nada',
'Spanish podcasts, remembered where you left off': 'Podcasts en español, que se acuerdan de dónde ibas',
'Search stations…': 'Buscar emisoras…',
'Search podcasts…': 'Buscar podcasts…',
'Search playlists…': 'Buscar listas…',
'Results for “{0}”': 'Resultados para “{0}”',
'No results for “{0}”.': 'Sin resultados para “{0}”.',
'Show more ({0})': 'Mostrar más ({0})',
'{0} shows': '{0} programas',
'Podcasts': 'Podcasts',
'Podcast': 'Podcast',
'Saved podcasts': 'Podcasts guardados',
+170 -59
View File
@@ -1,4 +1,19 @@
/* Música — the playlists a profile keeps, and the way to open them in Apple Music.
/* Música — three lists behind one search box: live radio, Spanish podcasts, and the Apple Music
* playlists a profile keeps.
*
* ── Why it is split into tabs at all ───────────────────────────────────────────────────────────
*
* It used to be one column: the radio, then the podcasts, then the playlists. Three lists of twenty
* rows each is a screen you scroll through looking for the thing you already knew you wanted — and
* the thing you wanted was usually at the bottom. So the screen asks first (Radio | Podcasts |
* Playlists) and shows one list at a time, ten rows long, with the search box above it and a
* "show more" under it. Nothing is hidden that cannot be reached in one tap, and nothing else is on
* screen while you are deciding.
*
* The search box searches whatever tab is open, and it searches the *source*, not the page: typing
* "jazz" asks the station directory, and typing "crimen" asks Apple's podcast directory — filtered,
* as always, to Spanish. The rows it returns are the same rows a category shows, so a station found
* by search is starred, played and cached exactly like one found by browsing.
*
* ── Why this is a list of links and not a MusicKit integration ─────────────────────────────────
*
@@ -23,10 +38,11 @@ import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { t } from '../lib/i18n.js'
import { confirmSheet } from '../sheets.jsx'
import { Button } from '../components/ui.jsx'
import { Button, Segmented, SearchField } from '../components/ui.jsx'
import Icon from '../components/Icon.jsx'
import { parseMusicUrl, profileUrl } from '../lib/music.js'
import { fmtClock, episodeMeta, resumeSeconds, isFinished } from '../lib/podcast-view.js'
import { PAGE, visible, hasMore, nextShown, hiddenCount } from '../lib/paging.js'
/** A playlist tile: artwork when the public page gave us some, a note when it did not. */
function PlaylistCard({ item, onRemove }) {
@@ -98,7 +114,7 @@ function AddPlaylistSheet({ close }) {
* worth ranking: SomaFM and Radio Paradise are listener-supported by mission, and the directory's
* thousands are mostly commercial broadcasters that may air ads.
*/
function RadioSection() {
function RadioSection({ q }) {
const radio = useUI(s => s.radio)
const playRadio = useUI(s => s.playRadio)
const toast = useUI(s => s.toast)
@@ -122,6 +138,7 @@ function RadioSection() {
sometimes a homepage rather than an image, which renders as a broken-image icon mid-list. A
row that fails falls back to the same placeholder as a row that never had one. */
const [noArt, setNoArt] = useState(() => new Set())
const [shown, setShown] = useState(PAGE)
const saved = (S.music && S.music.stations) || []
const load = key => {
@@ -131,11 +148,26 @@ function RadioSection() {
setGenres(r.genres)
setGenre(r.genre)
setStations(r.stations)
setShown(PAGE)
})
.catch(e => toast(e.message))
.finally(() => setBusy(false))
}
useEffect(() => { if (canRadio) load(null) }, [canRadio])
useEffect(() => { if (canRadio && !q) load(null) }, [canRadio])
/* A search replaces the list rather than filtering the twenty rows already on screen: the answer
to "jazz" is every jazz station in the directory, not the jazz stations that happened to be in
the genre you were looking at. Debounced, because every letter is a request. */
useEffect(() => {
if (!canRadio || !q) return
let live = true
setBusy(true)
api('/api/radio?q=' + encodeURIComponent(q))
.then(r => { if (live) { setStations(r.stations); setShown(PAGE) } })
.catch(e => { if (live) toast(e.message) })
.finally(() => { if (live) setBusy(false) })
return () => { live = false }
}, [canRadio, q])
const play = station => {
// Synchronous on purpose: `play()` has to happen inside this tap for iOS to allow it.
@@ -162,8 +194,10 @@ function RadioSection() {
</button>
</div>
const list = stations || []
return <>
<h4 className="sec">{t('Radio')}{stations ? <span className="vh-window"> · {t('{0} stations', stations.length)}</span> : null}</h4>
<h4 className="sec">{q ? t('Results for “{0}”', q) : t('Radio')}
{stations ? <span className="vh-window"> · {t('{0} stations', stations.length)}</span> : null}</h4>
{!canRadio
? <div className="small dim" style={{ margin: '0 2px 8px', lineHeight: 1.45 }}>
{staleApi
@@ -171,31 +205,41 @@ function RadioSection() {
: t('The radio comes from your server, so it needs a profile: sign in and the stations appear here.')}
</div>
: <>
<div className="small dim" style={{ margin: '0 2px 8px', lineHeight: 1.45 }}>
{!q && <div className="small dim" style={{ margin: '0 2px 8px', lineHeight: 1.45 }}>
{t('These are public radio streams: nothing is downloaded, and the audio goes straight from the station to your phone. The first four of each genre are stations with no advertising at all.')}
</div>
<div className="chips" style={{ marginBottom: 10 }}>
</div>}
{!q && <div className="chips" style={{ marginBottom: 10 }}>
{(genres || []).map(g => <button key={g.key}
className={'chip' + (genre === g.key ? ' on' : '')}
onClick={() => load(g.key)}>{g.label}</button>)}
</div>
{saved.length > 0 && <>
</div>}
{!q && saved.length > 0 && <>
<div className="mus-sub-h">{t('Saved stations')}</div>
{saved.map(st => row(st))}
</>}
{busy && !stations && <div className="small dim" style={{ margin: '0 2px 10px' }}>{t('Loading stations…')}</div>}
{stations && stations.map(st => row(st))}
{stations && !stations.length && <div className="small dim" style={{ margin: '0 2px 10px' }}>
{t('That station is not answering. Try another one.')}
{visible(list, shown).map(st => row(st))}
<More list={list} shown={shown} onMore={() => setShown(n => nextShown(n, list.length))} />
{stations && !list.length && <div className="small dim" style={{ margin: '0 2px 10px' }}>
{q ? t('No results for “{0}”.', q) : t('That station is not answering. Try another one.')}
</div>}
{radio && <div className="small dim" style={{ margin: '8px 2px 0' }}>
{radio.playing ? t('Playing {0}', radio.station.name) : t('Paused: {0}', radio.station.name)}
</div>}
{!radio && <div className="small dim" style={{ margin: '8px 2px 0' }}>{t('Nothing playing. Pick a station below.')}</div>}
{!q && (radio
? <div className="small dim" style={{ margin: '8px 2px 0' }}>
{radio.playing ? t('Playing {0}', radio.station.name) : t('Paused: {0}', radio.station.name)}
</div>
: <div className="small dim" style={{ margin: '8px 2px 0' }}>{t('Nothing playing. Pick a station below.')}</div>)}
</>}
</>
}
/** The house "show more": ten rows, then ten more, and the button says how many it is hiding. */
function More({ list, shown, onMore }) {
if (!hasMore(list, shown)) return null
return <div style={{ marginTop: 8, display: 'flex', justifyContent: 'center' }}>
<Button size="sm" onClick={onMore}>{t('Show more ({0})', hiddenCount(list, shown))}</Button>
</div>
}
/* ---------- podcasts ----------
*
* Spanish-language shows, by category, from Apple's directory (free, no key), with the episodes read
@@ -208,7 +252,7 @@ function RadioSection() {
* audio element in lib/player.js. Tapping an episode plays it inside the tap, which is the only way
* iOS lets audio start.
*/
function PodcastSection() {
function PodcastSection({ q }) {
const user = useStore(s => s.user)
const cfg = useStore(s => s.config)
const S = useStore(s => s.S)
@@ -222,6 +266,7 @@ function PodcastSection() {
const [shows, setShows] = useState(null)
const [busy, setBusy] = useState(false)
const [noArt, setNoArt] = useState(() => new Set())
const [shown, setShown] = useState(PAGE)
const saved = (S.podcasts && S.podcasts.shows) || []
// The same two situations the radio has, for the same reason: the list comes from the server, and
// a guest or an api older than the app must not look like a request that quietly failed.
@@ -235,11 +280,26 @@ function PodcastSection() {
setCategories(r.categories)
setCategory(r.category)
setShows(r.shows)
setShown(PAGE)
})
.catch(e => toast(e.message))
.finally(() => setBusy(false))
}
useEffect(() => { if (canPodcasts) load(null) }, [canPodcasts])
useEffect(() => { if (canPodcasts && !q) load(null) }, [canPodcasts])
/* Searching shows the same catalogue a category does, filtered by the same rules — the Spanish
check runs on a search result exactly as it does on a chart entry, which is the whole reason
both go through one function on the server. */
useEffect(() => {
if (!canPodcasts || !q) return
let live = true
setBusy(true)
api('/api/podcasts?q=' + encodeURIComponent(q))
.then(r => { if (live) { setShows(r.shows); setShown(PAGE) } })
.catch(e => { if (live) toast(e.message) })
.finally(() => { if (live) setBusy(false) })
return () => { live = false }
}, [canPodcasts, q])
const isSaved = show => saved.some(x => x.feed === show.feed)
@@ -260,8 +320,10 @@ function PodcastSection() {
</button>
</div>
const list = shows || []
return <>
<h4 className="sec">{t('Podcasts')}</h4>
<h4 className="sec">{q ? t('Results for “{0}”', q) : t('Podcasts')}
{shows ? <span className="vh-window"> · {t('{0} shows', shows.length)}</span> : null}</h4>
{!canPodcasts
? <div className="small dim" style={{ margin: '0 2px 8px', lineHeight: 1.45 }}>
{staleApi
@@ -269,22 +331,23 @@ function PodcastSection() {
: t('Podcasts come from your server, so they need a profile: sign in and the shows appear here.')}
</div>
: <>
<div className="small dim" style={{ margin: '0 2px 8px', lineHeight: 1.45 }}>
{!q && <div className="small dim" style={{ margin: '0 2px 8px', lineHeight: 1.45 }}>
{t('Spanish podcasts only, which is checked in each show’s own feed rather than assumed from the store. Nothing is downloaded: the episode goes straight from the publisher to your phone, and what you have heard is remembered per profile.')}
</div>
<div className="chips" style={{ marginBottom: 10 }}>
</div>}
{!q && <div className="chips" style={{ marginBottom: 10 }}>
{(categories || []).map(c => <button key={c.key}
className={'chip' + (category === c.key ? ' on' : '')}
onClick={() => load(c.key)}>{c.label}</button>)}
</div>
{saved.length > 0 && <>
</div>}
{!q && saved.length > 0 && <>
<div className="mus-sub-h">{t('Saved podcasts')}</div>
{saved.map(st => row(st))}
</>}
{busy && !shows && <div className="small dim" style={{ margin: '0 2px 10px' }}>{t('Loading podcasts…')}</div>}
{shows && shows.map(st => row(st))}
{shows && !shows.length && <div className="small dim" style={{ margin: '0 2px 10px' }}>
{t('No Spanish shows came back for this category. Try another one.')}
{visible(list, shown).map(st => row(st))}
<More list={list} shown={shown} onMore={() => setShown(n => nextShown(n, list.length))} />
{shows && !list.length && <div className="small dim" style={{ margin: '0 2px 10px' }}>
{q ? t('No results for “{0}”.', q) : t('No Spanish shows came back for this category. Try another one.')}
</div>}
</>}
</>
@@ -296,6 +359,8 @@ function ShowSheet({ show, close, progress }) {
const playEpisode = useUI(s => s.playEpisode)
const [data, setData] = useState(null)
const [err, setErr] = useState('')
// Forty episodes in a sheet is a wall with a scrollbar; ten and "show more" is a list.
const [shown, setShown] = useState(PAGE)
useEffect(() => {
let live = true
@@ -332,7 +397,7 @@ function ShowSheet({ show, close, progress }) {
{err && <div className="small dim" style={{ padding: '4px 2px' }}>{err}</div>}
{!data && !err && <div className="small dim" style={{ padding: '4px 2px' }}>{t('Reading the feed…')}</div>}
{data && <div className="pod-eps">
{data.episodes.map(ep => <button key={ep.id} className="pod-ep" onClick={() => play(ep)}>
{visible(data.episodes, shown).map(ep => <button key={ep.id} className="pod-ep" onClick={() => play(ep)}>
<Icon name="play" className="pod-ep-i" />
<span className="pod-ep-meta">
<span className="pod-ep-t">{ep.title}</span>
@@ -344,6 +409,7 @@ function ShowSheet({ show, close, progress }) {
</span>
</span>
</button>)}
<More list={data.episodes} shown={shown} onMore={() => setShown(n => nextShown(n, data.episodes.length))} />
</div>}
{data && !data.episodes.length && <div className="small dim" style={{ padding: '4px 2px' }}>
{t('That feed has no playable episodes in it — trailers only, or subscriber-only audio.')}
@@ -358,6 +424,22 @@ export default function Music() {
const removePlaylist = useStore(s => s.removePlaylist)
const list = (S.music && S.music.playlists) || []
const profile = profileUrl(S.music && S.music.user)
/* Radio first: it is the one that needs no account, no Apple Music, and no decision. */
const [tab, setTab] = useState('radio')
const [q, setQ] = useState('')
/* What the sections actually search on. Four hundred milliseconds: long enough that typing
"entrenamiento" is one request instead of fourteen, short enough that it feels like typing. */
const typed = q.trim()
const query = useDebounced(typed, 400)
/* One letter is not a search: it matches everything, and asking the directory to prove it costs a
request per keystroke for an answer nobody can use. Below two characters the screen keeps
showing what it was showing, which is also what makes the transition into a search calm. */
const searching = query.length >= 2
// The playlists are local links, so their search is local too — no request, no debounce needed.
const playlists = searching
? list.filter(p => [p.name, p.curator].filter(Boolean).join(' ').toLowerCase().includes(query.toLowerCase()))
: list
const [shownPlaylists, setShownPlaylists] = useState(PAGE)
const askRemove = item => confirmSheet({
title: t('Remove “{0}”?', item.name),
@@ -366,48 +448,77 @@ export default function Music() {
onConfirm: () => removePlaylist(item.id)
})
const placeholder = tab === 'radio' ? t('Search stations…') : tab === 'podcasts' ? t('Search podcasts…') : t('Search playlists…')
return <>
<div className="hdr">
<div style={{ flex: 1 }}>
<h1>{t('Music')}</h1>
<div className="sub">{list.length ? t('{0} playlists', list.length) : t('Your Apple Music, one tap away')}</div>
<div className="sub">{tab === 'radio' ? t('Live radio, nothing downloaded')
: tab === 'podcasts' ? t('Spanish podcasts, remembered where you left off')
: list.length ? t('{0} playlists', list.length) : t('Your Apple Music, one tap away')}</div>
</div>
<button className="iconbtn" onClick={() => openSheet(close => <AddPlaylistSheet close={close} />)} aria-label={t('Add a playlist')}><Icon name="plus" /></button>
<button className="iconbtn" onClick={() => nav('/settings')} aria-label={t('Settings')}><Icon name="gear" /></button>
</div>
{profile
? <a className="card mus-profile" href={profile} target="_blank" rel="noopener noreferrer">
<Icon name="personCircle" className="mus-profile-i" />
<span className="mus-meta">
<span className="mus-name">@{S.music.user}</span>
<span className="mus-sub">{t('Your public Apple Music profile')}</span>
</span>
<Icon name="chevronRight" className="mus-go" />
</a>
: <div className="card mus-hint">
<Icon name="music" className="mus-hint-i" />
<div>
<div className="mus-name">{t('Add your Apple Music profile')}</div>
<div className="small dim" style={{ lineHeight: 1.45 }}>
{t('Put your username in Settings and it becomes a link here. Apple has no way to publish your playlists automatically, so the ones you want on this screen are the ones you add.')}
<div style={{ marginBottom: 10 }}>
<SearchField value={q} onChange={e => setQ(e.target.value)} onClear={() => setQ('')} placeholder={placeholder} />
</div>
<Segmented className="mus-tabs" options={[
{ value: 'radio', label: t('Radio'), icon: 'music' },
{ value: 'podcasts', label: t('Podcasts'), icon: 'personCircle' },
{ value: 'playlists', label: t('Playlists'), icon: 'list' }
]} value={tab} onChange={v => { setTab(v); setQ('') }} />
{/* One list at a time. Switching tabs clears the search box, because a query typed for the
stations ("jazz") means nothing for the playlists, and a box that keeps it looks stuck. */}
{tab === 'radio' && <RadioSection q={searching ? query : ''} />}
{tab === 'podcasts' && <PodcastSection q={searching ? query : ''} />}
{tab === 'playlists' && <>
{profile
? <a className="card mus-profile" href={profile} target="_blank" rel="noopener noreferrer">
<Icon name="personCircle" className="mus-profile-i" />
<span className="mus-meta">
<span className="mus-name">@{S.music.user}</span>
<span className="mus-sub">{t('Your public Apple Music profile')}</span>
</span>
<Icon name="chevronRight" className="mus-go" />
</a>
: <div className="card mus-hint">
<Icon name="music" className="mus-hint-i" />
<div>
<div className="mus-name">{t('Add your Apple Music profile')}</div>
<div className="small dim" style={{ lineHeight: 1.45 }}>
{t('Put your username in Settings and it becomes a link here. Apple has no way to publish your playlists automatically, so the ones you want on this screen are the ones you add.')}
</div>
</div>
</div>
</div>}
</div>}
<RadioSection />
<PodcastSection />
<h4 className="sec">{t('Playlists')}</h4>
{list.length === 0
? <div className="empty">
<div className="ico"><Icon name="music" /></div>
{t('No playlists yet.')}<br />
<span className="small dim">{t('Add one from the + above.')}</span>
</div>
: list.map(item => <PlaylistCard key={item.id} item={item} onRemove={() => askRemove(item)} />)}
<h4 className="sec">{searching ? t('Results for “{0}”', query) : t('Playlists')}
{playlists.length ? <span className="vh-window"> · {t('{0} playlists', playlists.length)}</span> : null}</h4>
{playlists.length === 0
? (searching
? <div className="small dim" style={{ margin: '0 2px 10px' }}>{t('No results for “{0}”.', query)}</div>
: <div className="empty">
<div className="ico"><Icon name="music" /></div>
{t('No playlists yet.')}<br />
<span className="small dim">{t('Add one from the + above.')}</span>
</div>)
: visible(playlists, shownPlaylists).map(item => <PlaylistCard key={item.id} item={item} onRemove={() => askRemove(item)} />)}
<More list={playlists} shown={shownPlaylists} onMore={() => setShownPlaylists(n => nextShown(n, playlists.length))} />
</>}
<div style={{ height: 16 }} />
</>
}
/** A value, delayed: the search box types on every keystroke and the server should not hear them all. */
function useDebounced(value, ms) {
const [slow, setSlow] = useState(value)
useEffect(() => {
const id = setTimeout(() => setSlow(value), ms)
return () => clearTimeout(id)
}, [value, ms])
return slow
}
+152 -2
View File
@@ -53,7 +53,9 @@ beforeEach(() => {
api.mockResolvedValue({ genres: [], genre: null, stations: [] })
playStream.mockClear()
playFile.mockClear()
act(() => { useUI.setState({ radio: null }) })
/* The UI store is module-level, so a sheet left open by one test is still open for the next one:
`sheets` is part of the state that has to be reset, not just the player. */
act(() => { useUI.setState({ radio: null, pod: null, sheets: [] }) })
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
@@ -65,7 +67,9 @@ beforeEach(() => {
config: null
}))
})
afterEach(() => { act(() => root.unmount()); host.remove() })
/* `#modal-root` is created once by Modals and lives on the body, so a sheet left open by one test
is still in the DOM for the next one. */
afterEach(() => { act(() => root.unmount()); host.remove(); document.getElementById('modal-root')?.remove() })
/* The screen now asks two endpoints as well as the Apple Music lookup, so a test that cares about
one of them says what the others answer: a single `mockResolvedValue` for all of them made the
@@ -79,11 +83,28 @@ const stubApi = ({ radio = { genres: [], genre: null, stations: [] }, podcasts =
})
const mount = async () => { await act(async () => { root.render(<Music />) }) }
/* The screen shows one list at a time now, so a test says which one it means. */
const openTab = async name => {
const btn = [...host.querySelectorAll('.seg button')].find(b => b.textContent.includes(name))
act(() => { btn.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => { await Promise.resolve() })
}
/* Typing in a search box that is debounced by 400 ms, and waiting it out. */
const type = async text => {
const input = host.querySelector('.searchf input')
act(() => {
const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set
set.call(input, text)
input.dispatchEvent(new Event('input', { bubbles: true }))
})
await act(async () => { await new Promise(r => setTimeout(r, 450)) })
}
const links = () => [...host.querySelectorAll('a')]
describe('Música', () => {
it('says how to get a playlist when there are none', async () => {
await mount()
await openTab('Playlists')
expect(host.textContent).toContain('No playlists yet.')
expect(host.textContent).toContain('Add your Apple Music profile')
expect(links().length).toBe(0)
@@ -92,6 +113,7 @@ describe('Música', () => {
it('makes each playlist a link to its own Apple Music page', async () => {
useStore.setState(s => ({ S: { ...s.S, music: { user: 'ana', playlists: [item()] } } }))
await mount()
await openTab('Playlists')
const [profile, playlist] = links()
expect(profile.getAttribute('href')).toBe('https://music.apple.com/profile/ana')
expect(playlist.getAttribute('href')).toBe('https://music.apple.com/us/playlist/leg-day/pl.aaa')
@@ -106,6 +128,7 @@ describe('Música', () => {
it('removes one without touching the others', async () => {
useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [item(), item({ id: 'pl.bbb', name: 'Push Day' })] } } }))
await mount()
await openTab('Playlists')
expect(host.textContent).toContain('Leg Day')
act(() => { useStore.getState().removePlaylist('pl.aaa') })
await act(async () => {})
@@ -119,6 +142,7 @@ describe('Música', () => {
it('adds what the form was given, all the way through the sheet', async () => {
api.mockResolvedValue({ ok: true, meta: { title: 'Leg Day', artwork: 'https://is1-ssl.mzstatic.com/x/600x600bb.jpg', tracks: 42, curator: 'Ana' } })
await act(async () => { root.render(<><Music /><Modals /></>) })
await openTab('Playlists')
act(() => { [...document.querySelectorAll('button')].find(b => b.getAttribute('aria-label') === 'Add a playlist').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
const fields = [...document.querySelectorAll('#modal-root input')]
expect(fields.length).toBe(2) // the link, then the optional name
@@ -212,6 +236,7 @@ describe('Música', () => {
act(() => { useStore.getState().addPlaylist(item()) })
act(() => { useStore.getState().addPlaylist(item({ name: 'Leg Day (again)' })) })
await mount()
await openTab('Playlists')
expect(host.querySelectorAll('.mus-card').length).toBe(1)
expect(host.textContent).toContain('Leg Day')
})
@@ -226,6 +251,7 @@ describe('Música', () => {
it('lists the categories the server offers, and the Spanish shows in the first one', async () => {
stubApi({ podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } })
await mount()
await openTab('Podcasts')
const chips = [...host.querySelectorAll('.chips .chip')]
expect(chips.map(c => c.textContent)).toContain('Salud y fitness')
const rows = [...host.querySelectorAll('.mus-rad')]
@@ -238,6 +264,7 @@ describe('Música', () => {
it('saves a show with the star, and it comes back as a saved row', async () => {
stubApi({ podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } })
await mount()
await openTab('Podcasts')
const star = [...host.querySelectorAll('.mus-rad-save')].pop()
act(() => { star.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
@@ -254,6 +281,7 @@ describe('Música', () => {
// Ten minutes in, from a previous session on another device.
useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [] }, podcasts: { shows: [], progress: { 'ep-1': { pos: 600, dur: 3600, at: Date.now() } } } } }))
await act(async () => { root.render(<><Music /><Modals /></>) })
await openTab('Podcasts')
const rows = [...host.querySelectorAll('.mus-rad')]
act(() => { rows[rows.length - 1].querySelector('.mus-rad-main').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => { await Promise.resolve() })
@@ -276,6 +304,7 @@ describe('Música', () => {
show: { feed: 'https://a.example.com/feed', spanish: false, show: { title: 'English Show', language: 'en' }, episodes: [] }
})
await act(async () => { root.render(<><Music /><Modals /></>) })
await openTab('Podcasts')
const rows = [...host.querySelectorAll('.mus-rad')]
act(() => { rows[rows.length - 1].querySelector('.mus-rad-main').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => { await Promise.resolve() })
@@ -285,6 +314,7 @@ describe('Música', () => {
it('tells a guest where the podcasts come from, without asking the server', async () => {
useStore.setState({ user: null })
await mount()
await openTab('Podcasts')
expect(host.textContent).toContain('Podcasts come from your server, so they need a profile')
expect(api).not.toHaveBeenCalled()
})
@@ -292,9 +322,129 @@ describe('Música', () => {
it('says the server is older when it does not offer podcasts yet', async () => {
useStore.setState({ config: { features: ['vitals', 'radio'] } })
await mount()
await openTab('Podcasts')
expect(host.textContent).toContain('Your server has not been updated for the podcasts yet')
// The radio is offered by this server, so it asks; the podcasts are not, so they are not asked
// for at all — a chip that 404s is worse than a sentence that explains.
expect(api.mock.calls.some(c => String(c[0]).startsWith('/api/podcasts'))).toBe(false)
})
/* ---------- one list at a time, ten rows at a time, and a search box ---------- */
const station = i => ({
src: 'rb', id: 's' + i, name: 'Emisora ' + i, genre: 'jazz', detail: 'Argentina · MP3',
url: 'https://stream.example.com/' + i, image: null
})
const moreBtn = () => [...host.querySelectorAll('button')].find(b => b.textContent.startsWith('Show more'))
it('shows one list at a time, and the tab is what decides which', async () => {
stubApi({ radio: { genres: [], genre: 'workout', stations: [station(1)] }, podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } })
await mount()
expect(host.textContent).toContain('Emisora 1')
expect(host.querySelectorAll('.mus-rad')).toHaveLength(1)
await openTab('Podcasts')
// The stations are gone, not merely below the fold: that was the whole complaint about this
// screen — three long lists in one column, with what you wanted at the bottom.
expect(host.textContent).not.toContain('Emisora 1')
expect(host.textContent).toContain('Tiene Sentido')
expect(api.mock.calls.some(c => String(c[0]).startsWith('/api/podcasts'))).toBe(true)
})
it('shows ten rows and says how many it is hiding', async () => {
stubApi({ radio: { genres: [], genre: 'workout', stations: Array.from({ length: 25 }, (_, i) => station(i)) } })
await mount()
expect(host.querySelectorAll('.mus-rad')).toHaveLength(10)
expect(host.textContent).toContain('Emisora 9')
expect(host.textContent).not.toContain('Emisora 10')
expect(moreBtn().textContent).toBe('Show more (15)')
act(() => moreBtn().dispatchEvent(new MouseEvent('click', { bubbles: true })))
await act(async () => {})
expect(host.querySelectorAll('.mus-rad')).toHaveLength(20)
expect(moreBtn().textContent).toBe('Show more (5)')
act(() => moreBtn().dispatchEvent(new MouseEvent('click', { bubbles: true })))
await act(async () => {})
expect(host.querySelectorAll('.mus-rad')).toHaveLength(25)
// Nothing left to reveal, so the button is gone rather than sitting there doing nothing.
expect(moreBtn()).toBeUndefined()
})
it('pages the episodes of a show too, because forty rows is a wall', async () => {
const episodes = Array.from({ length: 23 }, (_, i) => ({ ...ep({ id: 'ep-' + i, title: 'Episodio ' + i }) }))
stubApi({
podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] },
show: { feed: 'https://a.example.com/feed', spanish: true, show: { title: 'Tiene Sentido' }, episodes }
})
await act(async () => { root.render(<><Music /><Modals /></>) })
await openTab('Podcasts')
const rows = [...host.querySelectorAll('.mus-rad')]
act(() => { rows[rows.length - 1].querySelector('.mus-rad-main').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => { await Promise.resolve() })
const sheet = document.querySelector('#modal-root')
expect(sheet.querySelectorAll('.pod-ep')).toHaveLength(10)
const more = [...sheet.querySelectorAll('button')].find(b => b.textContent.startsWith('Show more'))
expect(more.textContent).toBe('Show more (13)')
act(() => more.dispatchEvent(new MouseEvent('click', { bubbles: true })))
await act(async () => {})
expect(sheet.querySelectorAll('.pod-ep')).toHaveLength(20)
})
it('searches the station directory, not the page it is showing', async () => {
stubApi({ radio: { genres: [], genre: 'workout', stations: [station(1), station(2)] } })
await mount()
expect(host.querySelectorAll('.mus-rad')).toHaveLength(2)
api.mockImplementation(path => {
if (String(path).startsWith('/api/radio?q=')) return Promise.resolve({ ok: true, query: 'jazz', stations: [station(7)] })
return Promise.resolve({ ok: true })
})
await type('jazz')
// It asked the server for "jazz" — the answer is every jazz station in the directory, not the
// jazz stations that happened to be in the genre on screen.
expect(api.mock.calls.some(c => c[0] === '/api/radio?q=jazz')).toBe(true)
expect(host.textContent).toContain('Results for “jazz”')
expect(host.textContent).toContain('Emisora 7')
expect(host.textContent).not.toContain('Emisora 1')
// The genre chips step aside: they are for browsing, and this is not browsing.
expect(host.querySelectorAll('.chips .chip')).toHaveLength(0)
})
it('searches the podcast directory the same way, and says when there is nothing', async () => {
stubApi({ podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } })
await mount()
await openTab('Podcasts')
api.mockImplementation(path => {
if (String(path).startsWith('/api/podcasts?q=')) return Promise.resolve({ ok: true, query: 'zzz', shows: [] })
return Promise.resolve({ ok: true })
})
await type('zzz')
expect(api.mock.calls.some(c => c[0] === '/api/podcasts?q=zzz')).toBe(true)
expect(host.textContent).toContain('No results for “zzz”.')
// A query too short to search is not sent at all: one letter matches everything.
api.mockClear()
await type('z')
expect(api).not.toHaveBeenCalled()
})
it('searches the playlists locally, since they are links and not a directory', async () => {
useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [item(), item({ id: 'pl.bbb', name: 'Push Day', curator: null })] } } }))
stubApi({ podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } })
await mount()
await openTab('Playlists')
expect(host.querySelectorAll('.mus-card')).toHaveLength(2)
await type('push')
expect(host.querySelectorAll('.mus-card')).toHaveLength(1)
expect(host.textContent).toContain('Push Day')
expect(host.textContent).not.toContain('Leg Day')
// No request: this list is in the profile already.
expect(api.mock.calls.some(c => String(c[0]).includes('música'))).toBe(false)
await type('nada de nada')
expect(host.querySelectorAll('.mus-card')).toHaveLength(0)
expect(host.textContent).toContain('No results for “nada de nada”.')
})
})