Podcasts: en español solamente, y se acuerdan de dónde ibas
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

Música tiene una sección **Podcasts**: programas por categoría —Salud y fitness,
Deporte, Comedia, Noticias, Historia, Crímenes reales, Ciencia, Tecnología,
Sociedad y cultura, Negocios, Ficción, Educación, Música, Ocio— que suenan mientras
entrenás y siguen donde los dejaste. Sin dependencias nuevas y sin clave de API: el
directorio de Apple es público.

**En español se comprueba, no se supone.** La tienda dice dónde se *vende* un
podcast, no en qué idioma está —en el ranking español de comedia hay uno en catalán
y en el argentino uno en inglés—, así que se lee el `<language>` del feed de cada
programa (los primeros 64 KB, con una petición `Range`: el idioma está en las
primeras líneas) y se descarta lo que no sea español. Un feed sin etiqueta se queda:
feeds genuinamente españoles la omiten, y tirarlos por una omisión sería sacar
podcasts buenos de la lista. La respuesta cuenta cuántos quedaron afuera y por qué
(`skipped`), así que una lista corta nunca es un misterio, y abrir un programa en
otro idioma se contesta con `spanish:false` en vez de con una lista vacía.

Es la otra mitad de la radio y es lo contrario en todo lo que le importa al
reproductor: un podcast es un **archivo** —tiene principio, final y un minuto en el
que ibas—. Por eso hay un módulo de reglas puras (`lib/podcast-view.js`: dónde
retomar, qué cuenta como escuchado, cuál sigue, cuántas posiciones se guardan) y
por eso `lib/radio-player.js` pasa a ser `lib/player.js`: **un solo elemento de
audio** para las dos cosas, que es lo que impide que una emisora y un episodio suenen
a la vez. La barra crece línea de progreso, −15 s, +30 s, siguiente episodio y reloj;
la posición se guarda por perfil (con tope de 200, lo más nuevo primero) en pausa, al
parar, al terminar y cuando la app se va al fondo, porque con la pantalla bloqueada
iOS suspende los temporizadores y un guardado sólo desde el tick perdería lo
escuchado con el teléfono guardado. Media Session muestra episodio, programa y
progreso en la pantalla bloqueada.

Nada se descarga y nada pasa por el servidor: el episodio llega como la URL del
`enclosure` y el audio va de quien lo publica al teléfono. Acá no hay lista blanca
posible —un feed vive en cualquier host—, así que la puerta es **https, host real y
nunca una dirección privada**, comprobada en la URL y en dónde terminó el pedido, con
el cuerpo leído a tope y la conexión cortada al llegar: este contenedor vive adentro
de una casa.

Verificado con datos reales: 20 programas en español por categoría (idiomas es, es-ES,
es-mx), un feed de 40 episodios parseado, un feed en inglés contestado como
`spanish:false` y la dirección de metadatos rechazada con 400 sin hacer el pedido.

Fuera de los podcasts: la página de la API ocultaba `health` y `music` enteras —el
generador sólo dibuja las secciones de su tabla de etiquetas—, así que ahora están,
con radio y podcasts incluidas.
This commit is contained in:
dsantillan committed 2026-09-23 21:11:20 -04:00
1 parent a3e13df279
commit 22654c61fc
31 files changed
+3687 -360

No files matched your search

+5 -4
View File
@@ -20,7 +20,7 @@ import Modals from './components/Modals.jsx'
import Toast from './components/Toast.jsx'
import SyncBanner from './components/SyncBanner.jsx'
import RestTimer from './components/RestTimer.jsx'
import RadioBar from './components/RadioBar.jsx'
import PlayerBar from './components/PlayerBar.jsx'
import TimerFlash from './components/TimerFlash.jsx'
import Login from './views/Login.jsx'
import MobileOnboarding from './views/MobileOnboarding.jsx'
@@ -217,9 +217,10 @@ function Shell() {
{/* The chat owns the bottom of the screen: its composer sits where the tabs would be. */}
{loc.pathname !== '/coach' && <TabBar onStart={startFlow} />}
<RestTimer />
{/* The radio lives here, not in the Música screen: a player inside a route is unmounted when
somebody navigates away, and that is how music stops mid-set. */}
<RadioBar />
{/* The player bar lives here, not in the Música screen: a player inside a route is unmounted
when somebody navigates away, and that is how music stops mid-set — for a station and for
an episode alike. */}
<PlayerBar />
<Modals />
<Toast />
<TimerFlash />
+142
View File
@@ -0,0 +1,142 @@
/* The player bar: one line above the tab bar, while anything is playing.
*
* It follows the rest timer's shape on purpose — same place, same glass, same slide-up — because a
* second floating bar with its own look would read as a second app. What it adds is what is playing,
* what that thing says it is playing, and the buttons that matter.
*
* **The `<audio>` element is not here.** It lives in lib/player.js, outside React, so that changing
* screens cannot unmount it and stop the music — which is the whole reason this bar is mounted above
* the router instead of inside the Música screen. This component reads the store and draws; the
* player reports and the store decides.
*
* Two kinds of media, so two shapes of the same line:
*
* - **Radio** has no position and no end. The line under the station is what the station says it is
* playing — or the station's own description, never an invented track — and the buttons are
* pause and stop.
* - **An episode** has all of it: a length, a place you are in, a place you left off, and a next
* one. So the bar grows a progress hairline, −15 s and +30 s, and a next-episode button when the
* queue has one. The two seek buttons are written as text rather than drawn as icons: no arrow
* glyph says "fifteen seconds", and this row is used with a sweaty thumb.
*/
import { useEffect, useState } from 'react'
import { useUI } from '../store/useUI.js'
import { api } from '../lib/api.js'
import { t } from '../lib/i18n.js'
import { fmtClock, nextEpisode, progressPct } from '../lib/podcast-view.js'
import Icon from './Icon.jsx'
/* How often the station is asked what it is playing.
*
* Forty-five seconds: long enough to be polite to two community services that run on donations,
* short enough that the line is usually right by the time a song ends. Not zero — a station's
* current track is the thing that makes a radio feel alive — and not per second, which would be
* abusing somebody else's bandwidth for a caption.
*
* While the screen is locked iOS suspends these timers, so the line simply stops moving and the
* music keeps playing. When the person looks again the next tick fixes it. */
const NOW_EVERY_MS = 45000
export default function PlayerBar() {
const radio = useUI(s => s.radio)
const pod = useUI(s => s.pod)
const { toggleRadio, stopRadio, setRadioNow, togglePod, stopPod, podSeek, podNext } = useUI()
const on = !!radio || !!pod
// The page makes room for the bar while it is there, the same class trick the rest timer uses.
useEffect(() => {
document.body.classList.toggle('playing-media', on)
return () => document.body.classList.remove('playing-media')
}, [on])
if (radio) return <RadioLine radio={radio} onToggle={toggleRadio} onStop={stopRadio} onNow={setRadioNow} />
if (pod) return <EpisodeLine pod={pod} onToggle={togglePod} onStop={stopPod} onSeek={podSeek} onNext={podNext} />
return null
}
/* ---------- radio ---------- */
function RadioLine({ radio, onToggle, onStop, onNow }) {
const station = radio.station
// Poll for what is playing, only for the sources that publish it (the api answers null for the
// rest, which costs one small request and shows nothing).
useEffect(() => {
if (!radio.playing || !station) return
let live = true
const ask = () => api('/api/radio/now?src=' + encodeURIComponent(station.src) + '&id=' + encodeURIComponent(station.id))
.then(r => { if (live && r?.now) onNow(r.now) })
.catch(() => {})
ask()
const id = setInterval(ask, NOW_EVERY_MS)
return () => { live = false; clearInterval(id) }
}, [radio.playing, station?.src, station?.id])
const line = radio.now
? [radio.now.artist, radio.now.title].filter(Boolean).join(' · ')
: (station.detail || station.genre || t('Live radio'))
return <Bar
cover={radio.now?.cover || station.image || null}
name={station.name}
line={line}
label={radio.playing ? t('Pause') : t('Play')}
icon={radio.playing ? 'pause' : 'play'}
onToggle={onToggle}
progress={null}
actions={<button className="iconbtn plr-btn" onClick={onStop} aria-label={t('Stop')}>
<Icon name="xmark" />
</button>} />
}
/* ---------- an episode ---------- */
function EpisodeLine({ pod, onToggle, onStop, onSeek, onNext }) {
const pct = progressPct({ pos: pod.position, dur: pod.duration }, pod.duration)
const hasNext = !!nextEpisode(pod.queue, pod.episode.id)
const clock = Number.isFinite(pod.duration) && pod.duration > 0
? `${fmtClock(pod.position)} / ${fmtClock(pod.duration)}`
: fmtClock(pod.position)
return <Bar
cover={pod.episode.image || pod.show?.image || null}
name={pod.show?.name || t('Podcast')}
line={pod.episode.title}
sub={clock}
label={pod.playing ? t('Pause') : t('Play')}
icon={pod.playing ? 'pause' : 'play'}
onToggle={onToggle}
progress={pct}
actions={<>
<button className="plr-seek" onClick={() => onSeek(-15)} aria-label={t('15 seconds back')}>−15</button>
<button className="plr-seek" onClick={() => onSeek(30)} aria-label={t('30 seconds forward')}>+30</button>
{hasNext && <button className="iconbtn plr-btn" onClick={onNext} aria-label={t('Next episode')}>
<Icon name="chevronRight" />
</button>}
<button className="iconbtn plr-btn" onClick={onStop} aria-label={t('Stop')}>
<Icon name="xmark" />
</button>
</>} />
}
/** The line itself, shared by both: cover, two lines of text, the controls, a progress hairline. */
function Bar({ cover, name, line, sub, label, icon, onToggle, progress, actions }) {
/* Artwork that does not load. A directory entry's "logo" is sometimes a homepage rather than an
image, and a broken image in the bar looks worse than the placeholder — so whatever failed is
remembered and never asked for twice. */
const [noArt, setNoArt] = useState(null)
return <div id="player">
{cover && cover !== noArt
? <img className="plr-cover" src={cover} alt="" onError={() => setNoArt(cover)} />
: <span className="plr-cover plr-cover-ph"><Icon name="music" /></span>}
<span className="plr-meta">
<span className="plr-name">{name}</span>
<span className="plr-now">{line}{sub ? <span className="plr-clock"> · {sub}</span> : null}</span>
</span>
<button className="iconbtn plr-btn plr-toggle" onClick={onToggle} aria-label={label}>
<Icon name={icon} />
</button>
{actions}
{progress != null && <span className="plr-progress" style={{ width: Math.max(0, Math.min(100, progress)) + '%' }} />}
</div>
}
+183
View File
@@ -0,0 +1,183 @@
// @vitest-environment happy-dom
/* The player bar, in both of its shapes, and the four things about it that are invisible when wrong.
*
* One: it disappears completely when nothing is playing — a bar that renders empty would sit over
* the tab bar and eat taps. Two: pause *pauses* — the station stays, and so does the episode, which
* is the whole point of listening while training. Three: an episode's seek buttons seek, and the
* progress hairline is the position, since a podcast you cannot scrub is a podcast you do not use.
* Four: the bar is mounted above the router, so it must not care which screen is on.
*
* The `<audio>` element itself lives in lib/player.js, outside React (see the comment there), so it
* is mocked here: this file is about what the bar draws and what it asks the store to do. */
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useUI } from '../store/useUI.js'
const api = vi.fn()
vi.mock('../lib/api.js', () => ({ api: (...a) => api(...a) }))
const playStream = vi.fn(() => true)
const playFile = vi.fn(() => true)
const seekBy = vi.fn(() => 100)
vi.mock('../lib/player.js', () => ({
playStream: (...a) => playStream(...a),
playFile: (...a) => playFile(...a),
pausePlayer: vi.fn(),
resumePlayer: vi.fn(() => true),
seekBy: (...a) => seekBy(...a),
seekTo: vi.fn(() => 0),
playerTime: () => ({ position: 0, duration: null }),
setPlayerVolume: vi.fn(),
setStreamSession: vi.fn(),
setEpisodeSession: vi.fn(),
setSessionPosition: vi.fn(),
wireSessionHandlers: vi.fn(),
clearSession: vi.fn(),
onPlayer: () => () => {}
}))
const { default: PlayerBar } = await import('./PlayerBar.jsx')
const station = (over = {}) => ({
src: 'soma', id: 'beatblender', name: 'Beat Blender',
detail: 'A late night blend', genre: 'Electronic',
url: 'https://ice2.somafm.com/beatblender-128-mp3', image: null, ...over
})
const episode = (over = {}) => ({
id: 'ep-1', title: 'En el corazón del ajo', url: 'https://audio.example.com/1.mp3',
date: '2025-09-02T10:00:00.000Z', duration: 3135, image: null, ...over
})
const show = { feed: 'https://a.example.com/feed', name: 'Nadie Sabe Nada', image: null }
let host, root
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
api.mockReset()
api.mockResolvedValue({ ok: true, now: null })
playStream.mockClear()
playFile.mockClear()
seekBy.mockClear()
host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
act(() => { useUI.setState({ radio: null, pod: null }) })
})
afterEach(() => {
act(() => root.unmount())
host.remove()
document.body.classList.remove('playing-media')
})
const mount = async () => { await act(async () => { root.render(<PlayerBar />) }) }
const btn = label => [...host.querySelectorAll('#player button')].find(b => b.getAttribute('aria-label') === label)
describe('the player bar', () => {
it('draws nothing at all before something is playing', async () => {
await mount()
expect(host.querySelector('#player')).toBe(null)
expect(document.body.classList.contains('playing-media')).toBe(false)
})
it('names the station and what it says it is playing', async () => {
api.mockResolvedValue({ ok: true, now: { artist: 'The Orb', title: 'Little Fluffy Clouds' } })
act(() => { useUI.getState().playRadio(station()) })
await mount()
await act(async () => { await Promise.resolve() })
expect(host.querySelector('.plr-name').textContent).toBe('Beat Blender')
expect(host.querySelector('.plr-now').textContent).toBe('The Orb · Little Fluffy Clouds')
// The page makes room for the bar, the same class trick the rest timer uses.
expect(document.body.classList.contains('playing-media')).toBe(true)
// And it asked the station what is playing, instead of inventing a caption.
expect(api.mock.calls[0][0]).toBe('/api/radio/now?src=soma&id=beatblender')
})
it('pauses a station without losing it', async () => {
act(() => { useUI.getState().playRadio(station()) })
await mount()
act(() => { btn('Pause').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(useUI.getState().radio.playing).toBe(false)
expect(useUI.getState().radio.station.id).toBe('beatblender')
expect(btn('Play')).toBeTruthy()
})
it('stops a station and takes the bar with it', async () => {
act(() => { useUI.getState().playRadio(station()) })
await mount()
act(() => { btn('Stop').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useUI.getState().radio).toBe(null)
expect(host.querySelector('#player')).toBe(null)
expect(document.body.classList.contains('playing-media')).toBe(false)
})
/* ---------- an episode ---------- */
it('shows the episode, the show and how far into it you are', async () => {
act(() => { useUI.getState().playEpisode(show, episode({ duration: 3600 }), [episode({ duration: 3600 })]) })
await mount()
expect(host.querySelector('.plr-name').textContent).toBe('Nadie Sabe Nada')
expect(host.querySelector('.plr-now').textContent).toContain('En el corazón del ajo')
// The clock is the position out of the length — a podcast without one looks like a stream.
expect(host.querySelector('.plr-clock').textContent).toBe(' · 0:00 / 1:00:00')
expect(host.querySelector('.plr-progress')).toBeTruthy()
})
it('draws the position as a filled hairline, and no line at all for a stream', async () => {
act(() => { useUI.getState().playEpisode(show, episode({ duration: 3600 }), []) })
await mount()
act(() => { useUI.getState().setPodPlayback({ position: 900 }) })
await act(async () => {})
expect(host.querySelector('.plr-progress').style.width).toBe('25%')
// A station has no position to draw: no hairline, nothing to scrub.
act(() => { useUI.getState().playRadio(station()) })
await act(async () => {})
expect(host.querySelector('.plr-progress')).toBe(null)
})
it('seeks by the two amounts a podcast is actually driven with', async () => {
act(() => { useUI.getState().playEpisode(show, episode(), []) })
await mount()
// Through the store's own action, so this is the real path: button → store → element.
act(() => { btn('15 seconds back').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
act(() => { btn('30 seconds forward').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(seekBy.mock.calls.map(c => c[0])).toEqual([-15, 30])
// And the bar's own clock follows the element rather than its own arithmetic.
expect(useUI.getState().pod.position).toBe(100)
})
it('offers the next episode only when the queue has one', async () => {
const first = episode({ id: 'ep-1' })
const second = episode({ id: 'ep-2', title: 'Otro' })
act(() => { useUI.getState().playEpisode(show, first, [first, second]) })
await mount()
expect(btn('Next episode')).toBeTruthy()
act(() => { useUI.getState().playEpisode(show, second, [first, second]) })
await act(async () => {})
expect(btn('Next episode')).toBeUndefined()
})
it('pauses an episode without losing the position, and plays it again there', async () => {
act(() => { useUI.getState().playEpisode(show, episode(), []) })
await mount()
act(() => { useUI.getState().setPodPlayback({ position: 620 }) })
act(() => { btn('Pause').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(useUI.getState().pod.playing).toBe(false)
expect(useUI.getState().pod.position).toBe(620)
playFile.mockClear()
act(() => { btn('Play').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
// Started again where it was, not from the beginning.
expect(playFile).toHaveBeenCalledWith(episode().url, { startAt: 620 })
})
it('shows the placeholder when the artwork does not load', async () => {
act(() => { useUI.getState().playEpisode({ ...show, image: 'https://x/not-an-image' }, episode({ image: null }), []) })
await mount()
expect(host.querySelector('.plr-cover').tagName).toBe('IMG')
act(() => { host.querySelector('.plr-cover').dispatchEvent(new Event('error')) })
await act(async () => {})
const art = host.querySelector('.plr-cover')
expect(art.tagName).toBe('SPAN')
expect(art.classList.contains('plr-cover-ph')).toBe(true)
})
})
-77
View File
@@ -1,77 +0,0 @@
/* The radio bar: one line above the tab bar, while something is playing.
*
* It follows the rest timer's shape on purpose — same place, same glass, same slide-up — because a
* second floating bar with its own look would read as a second app. What it adds is the station,
* what the station says it is playing, and a pause button.
*
* The `<audio>` element is *not* here: it lives in lib/radio-player.js, outside React, so that
* changing screens cannot unmount it and stop the music. This component reads the store, draws the
* line, and asks it to poll the station for what is playing.
*/
import { useEffect, useState } from 'react'
import { useUI } from '../store/useUI.js'
import { api } from '../lib/api.js'
import { t } from '../lib/i18n.js'
import Icon from './Icon.jsx'
/* How often the station is asked what it is playing.
*
* Forty-five seconds: long enough to be polite to two community services that run on donations,
* short enough that the line is usually right by the time a song ends. Not zero — a station's
* current track is the thing that makes a radio feel alive — and not per second, which would be
* abusing somebody else's bandwidth for a caption.
*
* While the screen is locked iOS suspends these timers, so the line simply stops moving and the
* music keeps playing. When the person looks again the next tick fixes it. */
const NOW_EVERY_MS = 45000
export default function RadioBar() {
const radio = useUI(s => s.radio)
const { toggleRadio, stopRadio, setRadioNow } = useUI()
const station = radio?.station
/* A cover that did not load. A directory station's "logo" is sometimes a homepage URL rather than
an image, and a broken image in the bar is worse than the placeholder — so whatever failed is
remembered and never asked for twice. */
const [noArt, setNoArt] = useState(null)
// Poll for what is playing, only for the sources that publish it (the api answers null for the
// rest, which costs one small request and shows nothing).
useEffect(() => {
if (!radio?.playing || !station) return
let live = true
const ask = () => api('/api/radio/now?src=' + encodeURIComponent(station.src) + '&id=' + encodeURIComponent(station.id))
.then(r => { if (live && r?.now) setRadioNow(r.now) })
.catch(() => {})
ask()
const id = setInterval(ask, NOW_EVERY_MS)
return () => { live = false; clearInterval(id) }
}, [radio?.playing, station?.src, station?.id])
// The page makes room for the bar while it is there, the same class trick the rest timer uses.
useEffect(() => {
document.body.classList.toggle('radioing', !!radio)
return () => document.body.classList.remove('radioing')
}, [!!radio])
if (!radio) return null
const now = radio.now
const cover = now?.cover || station.image || null
const line = now ? [now.artist, now.title].filter(Boolean).join(' · ') : (station.detail || station.genre || t('Live radio'))
return <div id="radio">
{cover && cover !== noArt
? <img className="rad-cover" src={cover} alt="" onError={() => setNoArt(cover)} />
: <span className="rad-cover rad-cover-ph"><Icon name="music" /></span>}
<span className="rad-meta">
<span className="rad-name">{station.name}</span>
<span className="rad-now">{line}</span>
</span>
<button className="iconbtn rad-btn" onClick={toggleRadio}
aria-label={radio.playing ? t('Pause') : t('Play')}>
<Icon name={radio.playing ? 'pause' : 'play'} />
</button>
<button className="iconbtn rad-btn" onClick={stopRadio} aria-label={t('Stop')}>
<Icon name="xmark" />
</button>
</div>
}
-126
View File
@@ -1,126 +0,0 @@
// @vitest-environment happy-dom
/* The radio bar, and the two things about it that are easy to get wrong and invisible when wrong.
*
* One: it has to disappear completely when nothing is playing — a bar that renders empty would sit
* over the tab bar and eat taps. Two: the pause button has to *pause*, not stop: stopping drops the
* station, and the whole point of listening while training is that the same station is still there
* after the rest.
*
* The `<audio>` element itself lives in lib/radio-player.js, outside React (see the comment there),
* so it is mocked here — this file is about what the bar draws and what it asks the store to do. */
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useUI } from '../store/useUI.js'
const api = vi.fn()
vi.mock('../lib/api.js', () => ({ api: (...a) => api(...a) }))
const playStream = vi.fn(() => true)
vi.mock('../lib/radio-player.js', () => ({
playStream: (...a) => playStream(...a),
pauseStream: vi.fn(),
setStreamVolume: vi.fn(),
setMediaSession: vi.fn(),
clearMediaSession: vi.fn()
}))
const { default: RadioBar } = await import('./RadioBar.jsx')
const station = (over = {}) => ({
src: 'somafm', id: 'beatblender', name: 'Beat Blender',
detail: 'A late night blend', genre: 'Electronic',
url: 'https://ice2.somafm.com/beatblender-128-mp3', image: null, ...over
})
let host, root
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
api.mockReset()
api.mockResolvedValue({ ok: true, now: null })
playStream.mockClear()
host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
act(() => { useUI.setState({ radio: null }) })
})
afterEach(() => {
act(() => root.unmount())
host.remove()
document.body.classList.remove('radioing')
})
const mount = async () => { await act(async () => { root.render(<RadioBar />) }) }
const btn = label => [...host.querySelectorAll('#radio button')].find(b => b.getAttribute('aria-label') === label)
describe('the radio bar', () => {
it('draws nothing at all before something is playing', async () => {
await mount()
expect(host.querySelector('#radio')).toBe(null)
expect(document.body.classList.contains('radioing')).toBe(false)
})
it('names the station and what it says it is playing', async () => {
api.mockResolvedValue({ ok: true, now: { artist: 'The Orb', title: 'Little Fluffy Clouds' } })
act(() => { useUI.getState().playRadio(station()) })
await mount()
await act(async () => { await Promise.resolve() })
expect(host.querySelector('.rad-name').textContent).toBe('Beat Blender')
expect(host.querySelector('.rad-now').textContent).toBe('The Orb · Little Fluffy Clouds')
// The page makes room for the bar, the same class trick the rest timer uses.
expect(document.body.classList.contains('radioing')).toBe(true)
// And it asked the station what is playing, instead of inventing a caption.
expect(api.mock.calls[0][0]).toBe('/api/radio/now?src=somafm&id=beatblender')
})
it('falls back to what the station is when it publishes no track', async () => {
act(() => { useUI.getState().playRadio(station({ genre: 'Techno' })) })
await mount()
await act(async () => { await Promise.resolve() })
expect(host.querySelector('.rad-now').textContent).toBe('A late night blend')
})
it('pause keeps the station, so the same one is still there after the rest', async () => {
act(() => { useUI.getState().playRadio(station()) })
await mount()
act(() => { btn('Pause').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(useUI.getState().radio.playing).toBe(false)
expect(useUI.getState().radio.station.id).toBe('beatblender')
// Still on screen, still named, and the button now offers to start it again.
expect(host.querySelector('.rad-name').textContent).toBe('Beat Blender')
expect(btn('Play')).toBeTruthy()
})
it('stop takes the bar away with the station', async () => {
act(() => { useUI.getState().playRadio(station()) })
await mount()
act(() => { btn('Stop').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useUI.getState().radio).toBe(null)
expect(host.querySelector('#radio')).toBe(null)
expect(document.body.classList.contains('radioing')).toBe(false)
})
it('shows the station logo when the station publishes no track', async () => {
act(() => { useUI.getState().playRadio(station({ image: 'https://x/logo.png' })) })
await mount()
expect(host.querySelector('.rad-cover').getAttribute('src')).toBe('https://x/logo.png')
})
it('prefers the cover of the track it is playing over the station logo', async () => {
api.mockResolvedValue({ ok: true, now: { artist: 'A', title: 'B', cover: 'https://x/cover.jpg' } })
act(() => { useUI.getState().playRadio(station({ image: 'https://x/logo.png' })) })
await mount()
expect(host.querySelector('.rad-cover').getAttribute('src')).toBe('https://x/cover.jpg')
})
/* A directory station's "logo" is sometimes a homepage rather than an image, and a broken image
in the bar looks worse than no artwork at all. */
it('falls back to the placeholder when the artwork does not load', async () => {
act(() => { useUI.getState().playRadio(station({ image: 'https://x/not-an-image' })) })
await mount()
expect(host.querySelector('.rad-cover').tagName).toBe('IMG')
act(() => { host.querySelector('.rad-cover').dispatchEvent(new Event('error')) })
await act(async () => {})
const art = host.querySelector('.rad-cover')
expect(art.tagName).toBe('SPAN')
expect(art.classList.contains('rad-cover-ph')).toBe(true)
})
})
+54 -17
View File
@@ -1117,7 +1117,9 @@ body.chips-dragging *{cursor:inherit}
#timer .t{font-size:26px;font-weight:600;letter-spacing:-.026em;font-variant-numeric:tabular-nums;min-width:66px}
#timer .bar{flex:1;height:4px;background:var(--surface-3);border-radius:99px;overflow:hidden}
#timer .bar i{display:block;height:100%;background:var(--acc);transition:width 1s linear}
/* A station row: the whole row plays it, and a star saves it for this profile. */
/* A row in Música: a radio station (the whole row plays it) or a podcast (the whole row opens it),
with a star that saves it for this profile. One shape for both, because they are the same object
as far as the eye is concerned — a square logo, a name, a line of detail. */
.mus-rad{display:flex;align-items:center;gap:4px;margin-bottom:6px}
.mus-rad.on .mus-rad-n{color:var(--acc)}
.mus-rad-main{flex:1;min-width:0;display:flex;align-items:center;gap:10px;text-align:left;
@@ -1135,10 +1137,29 @@ body.chips-dragging *{cursor:inherit}
.mus-rad-save .icn{font-size:17px}
.mus-sub-h{font-size:12px;font-weight:600;color:var(--label-3);text-transform:uppercase;letter-spacing:.04em;margin:2px 2px 6px}
/* The radio bar: the rest timer's shape, lower in the stack. It sits above the tab bar and, when
/* The episodes sheet: a show's feed, newest first. Rows are buttons because the whole row plays the
episode — that tap is also the user gesture iOS requires before any audio may start. */
.pod-head{display:flex;align-items:center;gap:11px;padding:2px 2px 10px}
.pod-head-i{width:46px;height:46px;border-radius:10px;object-fit:cover;flex:0 0 auto}
.pod-head-n{font-size:15px;font-weight:650;color:var(--label)}
.pod-eps{display:flex;flex-direction:column;gap:5px}
.pod-ep{display:flex;align-items:flex-start;gap:10px;text-align:left;padding:9px 11px;border-radius:var(--r-md);
background:var(--glass);border:var(--hair) solid var(--sep-op)}
.pod-ep:active{background:var(--surface-3)}
.pod-ep-i{font-size:15px;color:var(--acc);flex:0 0 auto;margin-top:1px}
.pod-ep-meta{display:flex;flex-direction:column;gap:2px;min-width:0}
.pod-ep-t{font-size:13.5px;color:var(--label);line-height:1.3}
.pod-ep-s{font-size:11.5px;color:var(--label-3)}
.pod-heard{color:var(--acc)}
/* The player bar: the rest timer's shape, lower in the stack. It sits above the tab bar and, when
a rest countdown is also on screen, above that too — the countdown is the one you act on seconds
from now, so it keeps the lower slot. */
#radio{
from now, so it keeps the lower slot.
One bar for the radio and for a podcast, because there is one audio element behind both. The only
difference is that an episode has a length, so its bar carries a progress hairline (`.plr-progress`,
absolutely positioned along the bottom edge) and two text seek buttons. */
#player{
position:fixed;left:12px;right:12px;bottom:calc(88px + var(--sab));z-index:59;
background:color-mix(in srgb,var(--surface) 97%,transparent);
-webkit-backdrop-filter:saturate(180%) blur(10px);backdrop-filter:saturate(180%) blur(10px);
@@ -1146,22 +1167,38 @@ body.chips-dragging *{cursor:inherit}
display:flex;align-items:center;gap:10px;
box-shadow:0 12px 34px -8px rgba(0,0,0,.55);
animation:slideup var(--med) var(--ease);
overflow:hidden;
}
body.resting #radio{bottom:calc(190px + var(--sab))}
body.radioing #app{padding-bottom:calc(146px + var(--sab))}
body.resting #player{bottom:calc(190px + var(--sab))}
body.playing-media #app{padding-bottom:calc(146px + var(--sab))}
@media (min-width:1000px){
#radio{left:50%;right:auto;margin-left:-260px;width:520px;bottom:112px}
body.resting #radio{bottom:200px}
body.radioing #app{padding-bottom:calc(186px + var(--sab))}
#player{left:50%;right:auto;margin-left:-260px;width:520px;bottom:112px}
body.resting #player{bottom:200px}
body.playing-media #app{padding-bottom:calc(186px + var(--sab))}
}
.plr-cover{width:38px;height:38px;border-radius:8px;object-fit:cover;flex:0 0 auto;display:block}
.plr-cover-ph{display:flex;align-items:center;justify-content:center;background:var(--surface-3);color:var(--label-3)}
.plr-cover-ph .icn{font-size:18px}
.plr-meta{display:flex;flex-direction:column;min-width:0;flex:1;gap:1px}
.plr-name{font-size:13.5px;font-weight:600;color:var(--label);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.plr-now{font-size:11.5px;color:var(--label-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.plr-clock{color:var(--label-3);font-variant-numeric:tabular-nums}
.plr-btn{flex:0 0 auto;color:var(--label-2)}
.plr-btn .icn{font-size:20px}
/* −15 / +30 as text: no arrow glyph says "fifteen seconds", and this is a button used with a
sweaty thumb. A 34px target, which is the smallest one worth having in a gym. */
.plr-seek{
flex:0 0 auto;min-width:34px;height:34px;padding:0 6px;border-radius:10px;border:0;
background:var(--surface-3);color:var(--label);font:600 11.5px/1 var(--font);
font-variant-numeric:tabular-nums;cursor:pointer;
}
.plr-seek:active{background:var(--surface-2)}
/* The progress hairline: two pixels along the bottom edge of the bar, filled from the left. */
.plr-progress{
position:absolute;left:0;bottom:0;height:2px;
background:var(--acc);border-radius:0 2px 2px 0;
transition:width var(--fast) linear;
}
.rad-cover{width:38px;height:38px;border-radius:8px;object-fit:cover;flex:0 0 auto;display:block}
.rad-cover-ph{display:flex;align-items:center;justify-content:center;background:var(--surface-3);color:var(--label-3)}
.rad-cover-ph .icn{font-size:18px}
.rad-meta{display:flex;flex-direction:column;min-width:0;flex:1;gap:1px}
.rad-name{font-size:13.5px;font-weight:600;color:var(--label);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.rad-now{font-size:11.5px;color:var(--label-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.rad-btn{flex:0 0 auto;color:var(--label-2)}
.rad-btn .icn{font-size:20px}
/* rest variant: −15/+15/Skip and the clock won't share one line on a phone, so the clock and
bar take the top row and the controls take their own. The work timer keeps a single row —
it only ever has two buttons. */
+261
View File
@@ -0,0 +1,261 @@
/* player.js — the one `<audio>` element, for both the radio and the podcasts.
*
* Two kinds of media, one element, and the reasons are all about iOS:
*
* **It has to be one element.** A second `<audio>` competing for the audio session is how a phone
* ends up playing a station and an episode at once, or ducking one to silence. The store guarantees
* they are mutually exclusive; this module is the thing they share.
*
* **It has to be module-level, outside React.** An `<audio>` owned by a component is unmounted with
* it, which is how a player stops the moment somebody changes screens — and changing screens
* mid-session is the normal case in this app, not the edge case.
*
* **`play()` has to happen inside the tap.** iOS only allows audio to start from a user gesture, so
* nothing asynchronous may sit between the finger and the play: no fetch, no state update, no
* re-render. The radio therefore arrives with its stream URL already resolved, and an episode is a
* plain `https://` file URL, so both can be handed straight to `playStream`/`playFile`.
*
* A stream and a file are then treated differently on purpose:
*
* - A **stream** is endless: no duration, no seeking, nothing to resume. Position is meaningless.
* - A **file** has a length, a place you left off, and an end — so it reports time, accepts a
* seek, and applies a starting position. That is what makes resuming and "next episode" possible
* at all.
*
* Media Session is the other half of both: with metadata and action handlers set, iOS and Android
* show the station or the episode, with its progress, on the lock screen, and the sound keeps going
* with the phone in a pocket. While the screen is locked the browser suspends this page's timers, so
* the *caption* stops moving; the audio is played by the browser underneath, not by the page.
*/
let audio = null
let handlers = new Set()
/** The position a file should start at, kept until the browser knows its duration. */
let pendingStart = 0
function emit(event, extra = {}) {
const state = { position: positionOf(), duration: durationOf(), ...extra }
for (const h of [...handlers]) {
try { h(event, state) } catch { /* one listener throwing must not stop the others */ }
}
}
const positionOf = () => (audio && Number.isFinite(audio.currentTime) ? audio.currentTime : 0)
const durationOf = () => (audio && Number.isFinite(audio.duration) && audio.duration > 0 ? audio.duration : null)
/**
* The element, created on first use — there is no audio before somebody presses play.
*
* The event listeners are attached once, here, because every other function in this module is a
* thin command and the state of the player is only ever reported through them.
*/
export function playerEl() {
if (audio) return audio
if (typeof Audio === 'undefined') return null
audio = new Audio()
audio.preload = 'none'
// Radio has no end and no seeking: those two defaults are for files, and they make a stream
// misbehave on some browsers.
audio.loop = false
audio.addEventListener('timeupdate', () => emit('time'))
audio.addEventListener('play', () => emit('playing'))
audio.addEventListener('pause', () => emit('paused'))
audio.addEventListener('ended', () => emit('ended'))
audio.addEventListener('error', () => emit('error'))
audio.addEventListener('loadedmetadata', () => {
// The starting position of a file can only be applied once the browser knows how long it is.
if (pendingStart > 0 && audio.duration > 0) {
try { audio.currentTime = Math.min(pendingStart, Math.max(0, audio.duration - 1)) } catch { /* live stream */ }
pendingStart = 0
}
emit('meta')
})
return audio
}
/**
* Listen to the player. Returns the unsubscribe, and every handler is optional.
*
* Events: `playing`, `paused`, `time` (a position tick), `meta` (the length is known), `ended`,
* `error`. The second argument is always `{ position, duration }`.
*/
export function onPlayer(handler) {
if (typeof handler !== 'function') return () => {}
handlers.add(handler)
return () => handlers.delete(handler)
}
/** Start a live stream. Returns false when the browser refused, which the caller reports. */
export function playStream(url, volume = 1) {
const el = playerEl()
if (!el || !url) return false
pendingStart = 0
el.volume = volume
if (el.src !== url) el.src = url
return start(el)
}
/**
* Start a file — an episode — at `startAt` seconds in.
*
* The position is applied when the browser knows the duration, because assigning `currentTime` on a
* media element that has not loaded throws or is ignored depending on the browser.
*/
export function playFile(url, { startAt = 0, volume = 1 } = {}) {
const el = playerEl()
if (!el || !url) return false
el.volume = volume
if (el.src !== url) {
el.src = url
pendingStart = Math.max(0, Number(startAt) || 0)
} else if (startAt > 0 && Math.abs(el.currentTime - startAt) > 2) {
pendingStart = Number(startAt) || 0
}
if (pendingStart > 0 && el.readyState >= 1 && el.duration > 0) {
try { el.currentTime = Math.min(pendingStart, Math.max(0, el.duration - 1)) } catch { /* not seekable */ }
pendingStart = 0
}
return start(el)
}
function start(el) {
try {
const p = el.play()
// A rejected promise is the autoplay policy or a dead stream; either way the screen should not
// claim it is playing.
if (p && typeof p.catch === 'function') p.catch(() => emit('error'))
return true
} catch { return false }
}
/** Start the element again where it is — used by the lock screen's play button. */
export function resumePlayer() {
const el = playerEl()
return el ? start(el) : false
}
export function pausePlayer() {
try { audio?.pause() } catch { /* nothing playing */ }
}
/** Move inside the current file. Streams have no duration, so this does nothing on one. */
export function seekTo(seconds) {
if (!audio) return null
const dur = durationOf()
const target = Math.max(0, Math.min(Number(seconds) || 0, dur ? dur - 1 : Number.MAX_SAFE_INTEGER))
try { audio.currentTime = target } catch { return null }
emit('time')
return target
}
/** Fifteen seconds back is the most-used button in every podcast app ever made. */
export const seekBy = seconds => seekTo(positionOf() + (Number(seconds) || 0))
export const playerTime = () => ({ position: positionOf(), duration: durationOf() })
export function setPlayerVolume(volume) {
if (audio) audio.volume = Math.max(0, Math.min(1, Number(volume) || 0))
}
/**
* What the lock screen shows for a **station**. `now` is whatever the station publishes — SomaFM and
* Radio Paradise do, the directory's stations do not — and when there is none the station itself is
* the answer rather than an invented track.
*/
export function setStreamSession(station, now) {
setMetadata({
title: now?.title || station?.name || '',
artist: now?.artist || station?.genre || station?.detail || '',
album: 'KuentaGYM Radio',
artwork: now?.cover || station?.image || null
})
}
/** What the lock screen shows for an **episode**: the episode, the show, and where you are in it. */
export function setEpisodeSession(show, episode) {
setMetadata({
title: episode?.title || show?.name || '',
artist: show?.name || '',
album: 'KuentaGYM Podcasts',
artwork: episode?.image || show?.image || null
})
setSessionPosition()
}
function setMetadata({ title, artist, album, artwork }) {
const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
if (!ms) return
// Looked up per call rather than captured at load: a browser (or a test) that defines
// MediaMetadata later still gets a lock screen, and one without it keeps working the same way.
const Metadata = typeof MediaMetadata !== 'undefined' ? MediaMetadata : null
try {
if (Metadata) {
ms.metadata = new Metadata({
title: title || '',
artist: artist || '',
album,
artwork: /^https:\/\//i.test(artwork || '') ? [{ src: artwork, sizes: '512x512', type: 'image/jpeg' }] : []
})
}
} catch { /* a browser without Media Session simply shows nothing */ }
}
/**
* The lock screen's progress bar.
*
* Wrapped in a try/catch because `setPositionState` throws on anything it considers inconsistent
* (a position past the end, a zero duration, a missing one) and a lock screen is not worth an
* exception in the middle of a workout.
*/
export function setSessionPosition(duration = durationOf(), position = positionOf(), playbackRate = 1) {
const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
if (!ms?.setPositionState) return
try {
if (!Number.isFinite(duration) || duration <= 0) { ms.setPositionState(); return }
ms.setPositionState({
duration,
playbackRate,
position: Math.max(0, Math.min(Number(position) || 0, duration))
})
} catch { /* an older browser, or a state it did not like */ }
}
/* The handlers are how the lock screen's buttons reach this element. They are set once per session
rather than per track: `play` and `pause` mean the same thing for a station and an episode. */
let sessionWired = false
export function wireSessionHandlers() {
const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
if (!ms || sessionWired) return
sessionWired = true
try {
ms.setActionHandler?.('play', () => resumePlayer())
ms.setActionHandler?.('pause', () => pausePlayer())
ms.setActionHandler?.('stop', () => pausePlayer())
ms.setActionHandler?.('seekbackward', () => seekBy(-15))
ms.setActionHandler?.('seekforward', () => seekBy(30))
ms.setActionHandler?.('seekto', e => { if (e?.seekTime != null) seekTo(e.seekTime) })
} catch { /* a browser without those actions */ }
}
export function clearSession() {
const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
if (!ms) return
try {
ms.metadata = null
ms.setPositionState?.()
ms.setActionHandler?.('play', null)
ms.setActionHandler?.('pause', null)
ms.setActionHandler?.('stop', null)
ms.setActionHandler?.('seekbackward', null)
ms.setActionHandler?.('seekforward', null)
ms.setActionHandler?.('seekto', null)
} catch { /* as above */ }
}
/** Only for tests: forget the element and the listeners so each one starts clean. */
export function __resetPlayer() {
try { audio?.pause() } catch { /* nothing playing */ }
audio = null
handlers = new Set()
pendingStart = 0
sessionWired = false
}
+213
View File
@@ -0,0 +1,213 @@
// @vitest-environment happy-dom
/* The one audio element, and the file-vs-stream difference that decides whether podcasts work.
*
* What is tested here is the part that cannot be seen by tapping: that a file's starting position is
* applied *after* the browser knows the length (assigning `currentTime` before that is ignored or
* throws, per browser), that a seek is clamped inside the file, and that the lock screen's metadata
* and progress are set for both kinds of media — a podcast on a locked phone should show the
* episode, the show and how far in you are, not a blank rectangle.
*
* `duration` is a read-only getter in a DOM, so the tests define it on the element the way the
* browser fills it in and then dispatch the event that says so. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
playerEl, playStream, playFile, pausePlayer, resumePlayer, seekTo, seekBy, playerTime,
setPlayerVolume, onPlayer, setStreamSession, setEpisodeSession, setSessionPosition,
wireSessionHandlers, clearSession, __resetPlayer
} from './player.js'
/** Pretend the browser finished loading a file of this length. */
function pretendLoaded(el, seconds) {
Object.defineProperty(el, 'duration', { value: seconds, configurable: true })
el.dispatchEvent(new Event('loadedmetadata'))
}
let session
beforeEach(() => {
__resetPlayer()
session = { metadata: null, position: null, handlers: {}, setPositionState (s) { this.position = s ?? null } }
session.setActionHandler = (name, fn) => { session.handlers[name] = fn }
Object.defineProperty(navigator, 'mediaSession', { value: session, configurable: true })
// happy-dom has neither, and both are what a phone actually has: the metadata object the lock
// screen is handed, and the session it hangs off.
vi.stubGlobal('MediaMetadata', class { constructor(o) { Object.assign(this, o) } })
})
afterEach(() => { __resetPlayer(); delete navigator.mediaSession; vi.unstubAllGlobals() })
describe('one element for everything', () => {
it('is created once and shared, so a station and an episode never play at the same time', () => {
const a = playerEl()
expect(a).toBe(playerEl())
__resetPlayer()
expect(playerEl()).not.toBe(a)
expect(playerEl).toBeTruthy()
})
it('hands a station straight to play, inside the tap that asked for it', () => {
const el = playerEl()
const play = vi.spyOn(el, 'play')
expect(playStream('https://ice2.somafm.com/x-128-mp3', 0.6)).toBe(true)
expect(el.src).toBe('https://ice2.somafm.com/x-128-mp3')
expect(el.volume).toBe(0.6)
expect(play).toHaveBeenCalled()
expect(playStream('', 1)).toBe(false)
})
it('refuses to claim it is playing when the browser rejects the play', () => {
const el = playerEl()
el.play = () => { throw new Error('not allowed') }
expect(playStream('https://x/1.mp3')).toBe(false)
})
})
describe('a file, which is what an episode is', () => {
it('applies the starting position only once the length is known', () => {
const el = playerEl()
playFile('https://audio.example.com/1.mp3', { startAt: 600 })
expect(el.src).toBe('https://audio.example.com/1.mp3')
// Nothing yet: the browser has no duration, so a seek here would be ignored or throw.
expect(el.currentTime).toBe(0)
pretendLoaded(el, 3135)
expect(el.currentTime).toBe(600)
})
it('starts a file from the beginning when the saved position was past its end', () => {
const el = playerEl()
playFile('https://audio.example.com/1.mp3', { startAt: 99999 })
expect(el.currentTime).toBe(0, 'no seek before metadata')
pretendLoaded(el, 3135)
// Clamped inside the file rather than to its exact end, which some browsers treat as "finished".
expect(el.currentTime).toBe(3134)
})
it('reports the position and the length together', () => {
const el = playerEl()
playFile('https://audio.example.com/1.mp3')
expect(playerTime()).toEqual({ position: 0, duration: null })
pretendLoaded(el, 1200)
expect(playerTime()).toEqual({ position: 0, duration: 1200 })
})
it('seeks forward and back inside the file, and never outside it', () => {
const el = playerEl()
playFile('https://audio.example.com/1.mp3')
pretendLoaded(el, 1200)
el.currentTime = 100
expect(seekBy(15)).toBe(115)
expect(seekBy(-15)).toBe(100)
// Fifteen back from the first seconds lands at zero, not at a negative position.
expect(seekTo(5)).toBe(5)
expect(seekBy(-15)).toBe(0)
expect(seekTo(99999)).toBe(1199)
expect(seekTo(-5)).toBe(0)
})
it('resumes where it is, which is what the lock screen asks for', () => {
const el = playerEl()
const play = vi.spyOn(el, 'play')
el.currentTime = 42
expect(resumePlayer()).toBe(true)
expect(play).toHaveBeenCalled()
expect(el.currentTime).toBe(42)
pausePlayer()
})
it('clamps the volume', () => {
const el = playerEl()
setPlayerVolume(0.4)
expect(el.volume).toBe(0.4)
setPlayerVolume(9)
expect(el.volume).toBe(1)
setPlayerVolume('x')
expect(el.volume).toBe(0)
})
})
describe('what the rest of the app hears', () => {
it('reports playing, paused, time and the end of an episode', () => {
const el = playerEl()
const seen = []
const off = onPlayer((event, state) => seen.push([event, state.position, state.duration]))
pretendLoaded(el, 300)
el.dispatchEvent(new Event('play'))
el.dispatchEvent(new Event('timeupdate'))
el.dispatchEvent(new Event('pause'))
el.dispatchEvent(new Event('ended'))
expect(seen.map(s => s[0])).toEqual(['meta', 'playing', 'time', 'paused', 'ended'])
expect(seen[0][2]).toBe(300)
off()
el.dispatchEvent(new Event('timeupdate'))
expect(seen.length).toBe(5)
})
it('keeps going when one listener throws', () => {
const el = playerEl()
const other = vi.fn()
onPlayer(() => { throw new Error('boom') })
onPlayer(other)
el.dispatchEvent(new Event('play'))
expect(other).toHaveBeenCalled()
})
})
describe('the lock screen', () => {
it('shows the station, and the track when the station publishes one', () => {
setStreamSession({ name: 'Beat Blender', genre: 'Electronic', image: 'https://x/logo.png' })
expect(session.metadata.title).toBe('Beat Blender')
expect(session.metadata.artist).toBe('Electronic')
setStreamSession({ name: 'Beat Blender' }, { artist: 'Tycho', title: 'From Home', cover: 'https://x/c.jpg' })
expect(session.metadata.title).toBe('From Home')
expect(session.metadata.artist).toBe('Tycho')
})
it('shows the episode and the show, and how far into it you are', () => {
const el = playerEl()
playFile('https://audio.example.com/1.mp3')
pretendLoaded(el, 3600)
el.currentTime = 900
setEpisodeSession({ name: 'Tiene Sentido', image: 'https://x/show.jpg' }, { title: 'Episodio 12' })
expect(session.metadata.title).toBe('Episodio 12')
expect(session.metadata.artist).toBe('Tiene Sentido')
expect(session.position).toEqual({ duration: 3600, position: 900, playbackRate: 1 })
})
it('does not set a position state it cannot justify, and never throws on one', () => {
// A live stream has no duration: no progress bar, and `setPositionState()` with nothing is how
// it is cleared.
expect(() => setSessionPosition(null, 0)).not.toThrow()
expect(session.position).toBe(null)
// A duration of zero, or a position past the end, is exactly what the API throws on.
expect(() => setSessionPosition(0, 10)).not.toThrow()
session.setPositionState = () => { throw new Error('InvalidStateError') }
expect(() => setSessionPosition(100, 500)).not.toThrow()
})
it('puts the lock screen buttons on the element, once', () => {
const el = playerEl()
wireSessionHandlers()
wireSessionHandlers()
expect(typeof session.handlers.pause).toBe('function')
expect(typeof session.handlers.seekbackward).toBe('function')
playFile('https://audio.example.com/1.mp3')
pretendLoaded(el, 600)
el.currentTime = 100
session.handlers.seekbackward()
expect(el.currentTime).toBe(85)
session.handlers.seekforward()
expect(el.currentTime).toBe(115)
session.handlers.seekto({ seekTime: 300 })
expect(el.currentTime).toBe(300)
const pause = vi.spyOn(el, 'pause')
session.handlers.pause()
expect(pause).toHaveBeenCalled()
})
it('clears everything when the player is stopped', () => {
setStreamSession({ name: 'Beat Blender' })
wireSessionHandlers()
clearSession()
expect(session.metadata).toBe(null)
expect(session.handlers.play).toBe(null)
expect(session.handlers.pause).toBe(null)
})
})
+127
View File
@@ -0,0 +1,127 @@
/* The rules behind the podcast player: where to resume, how long an episode is, what comes next.
*
* A stream needs none of this — radio has no position, no end and nothing to continue — but every
* one of these is the difference between a podcast app you use and one you fight with while your
* hands are on a bar:
*
* - **Resume.** Coming back to a 50-minute episode must not mean finding your place again. The
* position is kept per episode, in the profile, and this decides when it is worth using.
* - **Almost finished is finished.** Resuming 20 seconds before the end is a worse experience than
* starting over, and it also leaves an episode that always looks unplayed.
* - **Next.** Episodes are made in order; the end of one should be the start of the next.
*
* All of it is pure and tested, because "started the wrong episode halfway through" is not something
* anybody reports as a bug — they just stop using the feature. */
import { fmtDate } from './format.js'
/** Resume under this many seconds in: not worth it, start from the beginning. */
export const MIN_RESUME = 30
/** Within this much of the end, the episode counts as finished. */
export const END_SLACK = 20
/** Positions kept per profile. Unbounded growth in a synced document is a slow, silent leak. */
export const MAX_PROGRESS = 200
/** `52:15`, `1:02:03` — the clock a player shows, not a human summary. */
export function fmtClock(seconds) {
const s = Math.max(0, Math.floor(Number(seconds) || 0))
const h = Math.floor(s / 3600)
const m = Math.floor((s % 3600) / 60)
const ss = String(s % 60).padStart(2, '0')
return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
}
/** `52 min`, `1h 12m` — what an episode's length reads as in a list. Null when the feed said nothing. */
export function fmtLength(seconds) {
if (!Number.isFinite(seconds) || seconds <= 0) return null
// A trailer is under a minute and should not round up to "1 min".
if (seconds < 60) return '<1 min'
const m = Math.round(seconds / 60)
return m >= 60 ? `${Math.floor(m / 60)}h ${m % 60}m` : `${m} min`
}
/**
* The second line of an episode row: the date it came out, and how long it is.
*
* Either half can be missing — plenty of feeds publish no `pubDate`, and `itunes:duration` is
* optional — so the separator only appears when there is something on both sides of it.
*/
export function episodeMeta(ep) {
const date = typeof ep?.date === 'string' && /^\d{4}-\d{2}-\d{2}/.test(ep.date)
? fmtDate(ep.date.slice(0, 10), false, true)
: null
return [date, fmtLength(ep?.duration)].filter(Boolean).join(' · ')
}
/** Where to start an episode, given what was saved for it before. 0 means "from the beginning". */
export function resumeSeconds(entry, duration) {
const pos = Number(entry?.pos)
if (!Number.isFinite(pos) || pos < MIN_RESUME) return 0
const dur = Number(duration ?? entry?.dur)
// A finished episode starts over: resuming into the last twenty seconds is a puzzle, not a
// feature, and it also leaves an episode that looks permanently unplayed.
if (Number.isFinite(dur) && dur > 0 && pos >= dur - END_SLACK) return 0
return pos
}
/** How far through the episode is, 0-100, or null when the length is unknown. */
export function progressPct(entry, duration) {
const dur = Number(duration ?? entry?.dur)
const pos = Number(entry?.pos)
if (!Number.isFinite(dur) || dur <= 0 || !Number.isFinite(pos)) return null
return Math.max(0, Math.min(100, (pos / dur) * 100))
}
/** Played to (near enough) the end. Used to mark a row as heard rather than to stop anything. */
export function isFinished(entry, duration) {
const dur = Number(duration ?? entry?.dur)
const pos = Number(entry?.pos)
if (!Number.isFinite(dur) || dur <= 0 || !Number.isFinite(pos)) return false
return pos >= dur - END_SLACK
}
/** The episode after this one in the queue, or null at the end of it. No wrapping. */
export function nextEpisode(queue, currentId) {
const list = Array.isArray(queue) ? queue : []
const i = list.findIndex(e => e && e.id === currentId)
return i >= 0 && i + 1 < list.length ? list[i + 1] : null
}
/** The episode before this one, or null. Used by the bar's back button. */
export function prevEpisode(queue, currentId) {
const list = Array.isArray(queue) ? queue : []
const i = list.findIndex(e => e && e.id === currentId)
return i > 0 ? list[i - 1] : null
}
/** The queue an episode was started from: the list it was tapped in, in the order it was shown. */
export function queueFor(episodes, episode) {
const list = Array.isArray(episodes) ? episodes.filter(Boolean) : []
return list.some(e => e.id === episode?.id) ? list : [episode].filter(Boolean)
}
/**
* Keep the newest `max` positions and forget the rest.
*
* `at` is when the position was last written; the oldest entries go first, so somebody with years of
* listening keeps the episodes they are actually in the middle of.
*/
export function trimProgress(progress, max = MAX_PROGRESS) {
const entries = Object.entries(progress || {})
if (entries.length <= max) return progress || {}
/* Newest first, and on a tie the later entry wins: several positions can be written inside the
same millisecond, and an object's own order is insertion order — so the tie-break is exactly
"the one saved most recently", instead of leaving the outcome to the sort's stability. */
return Object.fromEntries(entries
.map(([key, value], i) => ({ key, value, at: Number(value?.at) || 0, i }))
.sort((a, b) => (b.at - a.at) || (b.i - a.i))
.slice(0, max)
.map(e => [e.key, e.value]))
}
/** Whether a position is worth writing down at all: a two-second tap on play is not progress. */
export function worthSaving(entry, duration) {
const pos = Number(entry?.pos)
if (!Number.isFinite(pos) || pos < 5) return false
const dur = Number(duration ?? entry?.dur)
return !(Number.isFinite(dur) && dur > 0 && pos >= dur - END_SLACK)
}
+116
View File
@@ -0,0 +1,116 @@
/* The podcast player's rules, tested — because none of them fail loudly.
*
* `isFinished` and `resumeSeconds` are the pair that matter: resuming 15 seconds before the end, or
* marking a half-heard episode as heard, are both bugs that look like the app being stubborn rather
* than broken, and nobody reports those. */
import { describe, expect, it } from 'vitest'
import {
MIN_RESUME, END_SLACK, MAX_PROGRESS, fmtClock, fmtLength, episodeMeta, resumeSeconds,
progressPct, isFinished, nextEpisode, prevEpisode, queueFor, trimProgress, worthSaving
} from './podcast-view.js'
const ep = (over = {}) => ({ id: 'e1', title: 'Un episodio', url: 'https://a/1.mp3', date: '2025-09-12T10:00:00.000Z', duration: 3135, ...over })
describe('how an episode reads', () => {
it('shows a clock, not a human summary', () => {
expect(fmtClock(3135)).toBe('52:15')
expect(fmtClock(3723)).toBe('1:02:03')
expect(fmtClock(59)).toBe('0:59')
expect(fmtClock(0)).toBe('0:00')
expect(fmtClock(-5)).toBe('0:00')
expect(fmtClock(undefined)).toBe('0:00')
})
it('summarises a length the way a list wants it', () => {
expect(fmtLength(3135)).toBe('52 min')
expect(fmtLength(7200)).toBe('2h 0m')
expect(fmtLength(30)).toBe('<1 min')
// A feed that declares no duration gets no invented one.
expect(fmtLength(null)).toBe(null)
expect(fmtLength(0)).toBe(null)
})
it('puts the date and the length on one line, and works when either is missing', () => {
expect(episodeMeta(ep())).toContain('52 min')
expect(episodeMeta(ep())).toMatch(/2025/)
expect(episodeMeta(ep({ duration: null }))).not.toContain('·')
expect(episodeMeta(ep({ date: null }))).toBe('52 min')
expect(episodeMeta(ep({ date: null, duration: null }))).toBe('')
expect(episodeMeta(null)).toBe('')
})
})
describe('picking up where you left off', () => {
it('resumes a real position', () => {
expect(resumeSeconds({ pos: 600, dur: 3135 }, 3135)).toBe(600)
})
it('does not bother for the first few seconds', () => {
expect(resumeSeconds({ pos: MIN_RESUME - 1 }, 3135)).toBe(0)
expect(resumeSeconds({ pos: 0 }, 3135)).toBe(0)
expect(resumeSeconds(null, 3135)).toBe(0)
expect(resumeSeconds({ pos: 'x' }, 3135)).toBe(0)
})
it('starts a finished episode over instead of resuming into its last seconds', () => {
expect(resumeSeconds({ pos: 3135 - END_SLACK, dur: 3135 }, 3135)).toBe(0)
expect(resumeSeconds({ pos: 3130 }, 3135)).toBe(0)
// With no length stored, the position is all there is to go on — and it is used.
expect(resumeSeconds({ pos: 3130 }, null)).toBe(3130)
})
it('counts an episode near its end as finished, and a shorter one is not', () => {
expect(isFinished({ pos: 3130, dur: 3135 }, 3135)).toBe(true)
expect(isFinished({ pos: 3000, dur: 3135 }, 3135)).toBe(false)
expect(isFinished({ pos: 600 }, null)).toBe(false)
expect(isFinished(null, 3135)).toBe(false)
})
it('reports progress as a percentage, and refuses to invent a length', () => {
expect(progressPct({ pos: 1567, dur: 3134 }, 3134)).toBeCloseTo(50, 0)
expect(progressPct({ pos: 9999, dur: 3134 }, 3134)).toBe(100)
expect(progressPct({ pos: 100 }, null)).toBe(null)
expect(progressPct(null, 3134)).toBe(null)
})
it('only writes down a position worth having', () => {
expect(worthSaving({ pos: 4 }, 3135)).toBe(false)
expect(worthSaving({ pos: 5 }, 3135)).toBe(true)
// The last seconds of an episode are not a position to come back to.
expect(worthSaving({ pos: 3131 }, 3135)).toBe(false)
expect(worthSaving({ pos: 60 }, null)).toBe(true)
})
})
describe('the queue', () => {
const a = ep({ id: 'a' }), b = ep({ id: 'b' }), c = ep({ id: 'c' })
it('goes to the next episode, and stops at the end', () => {
expect(nextEpisode([a, b, c], 'a').id).toBe('b')
expect(nextEpisode([a, b, c], 'c')).toBe(null)
expect(nextEpisode([a, b, c], 'nope')).toBe(null)
expect(nextEpisode(null, 'a')).toBe(null)
})
it('goes back, and stops at the beginning', () => {
expect(prevEpisode([a, b, c], 'c').id).toBe('b')
expect(prevEpisode([a, b, c], 'a')).toBe(null)
})
it('plays an episode that was not in the list it came from, on its own', () => {
expect(queueFor([a, b], a).map(e => e.id)).toEqual(['a', 'b'])
const orphan = ep({ id: 'z' })
expect(queueFor([a, b], orphan).map(e => e.id)).toEqual(['z'])
expect(queueFor(null, a).map(e => e.id)).toEqual(['a'])
})
it('keeps the newest positions and lets the old ones go', () => {
const many = Object.fromEntries(Array.from({ length: MAX_PROGRESS + 20 }, (_, i) => ['e' + i, { pos: 10, at: i }]))
const kept = trimProgress(many)
expect(Object.keys(kept).length).toBe(MAX_PROGRESS)
expect(kept['e' + (MAX_PROGRESS + 19)]).toBeTruthy() // the most recent
expect(kept.e0).toBeUndefined() // and the oldest is gone
expect(trimProgress({ a: { pos: 1 } })).toEqual({ a: { pos: 1 } })
expect(trimProgress(null)).toEqual({})
})
})
-94
View File
@@ -1,94 +0,0 @@
/* radio-player.js — the one `<audio>` element, and the lock screen.
*
* A module of its own, and a module-level element, for one reason that decides whether this feature
* works at all on an iPhone: **`play()` has to be called inside the tap's own task.** iOS only lets
* audio start from a gesture, so anything asynchronous between the press and the play — a fetch, a
* state update, a re-render — is a press that does nothing. The stream URL therefore arrives with
* the station (the api resolves it when it builds the list), the press calls `play()` synchronously
* on this element, and the store only records what happened afterwards.
*
* The element lives outside React on purpose. An `<audio>` owned by a component is unmounted when
* that component is, which is how a player stops the moment somebody changes screens; this one
* survives every navigation, which is what makes listening while training possible.
*
* Media Session is the other half: with metadata and action handlers set, iOS and Android show the
* station, the track and the controls on the lock screen, and the music keeps playing with the
* phone in a pocket.
*/
const MEDIA_METADATA = typeof MediaMetadata !== 'undefined' ? MediaMetadata : null
let audio = null
/** The element, created on first use — there is no audio before somebody presses play. */
export function radioAudio() {
if (audio) return audio
if (typeof Audio === 'undefined') return null
audio = new Audio()
audio.preload = 'none'
// Radio has no end, and no seeking: those two defaults are for files, and they make a stream
// misbehave on some browsers.
audio.loop = false
return audio
}
/** Start a stream. Returns false when the browser refused, which the caller reports. */
export function playStream(url, volume = 1) {
const el = radioAudio()
if (!el || !url) return false
el.volume = volume
if (el.src !== url) el.src = url
try {
const p = el.play()
// A rejected promise is the autoplay policy or a dead stream; either way the screen should not
// claim it is playing.
if (p && typeof p.catch === 'function') p.catch(() => {})
return true
} catch { return false }
}
export function pauseStream() {
try { audio?.pause() } catch { /* nothing playing */ }
}
export function setStreamVolume(volume) {
if (audio) audio.volume = Math.max(0, Math.min(1, Number(volume) || 0))
}
/**
* What the lock screen shows. `now` is whatever the station publishes — SomaFM and Radio Paradise
* do, the directory's stations do not — and when there is none the station itself is the answer
* rather than an invented track.
*/
export function setMediaSession(station, now) {
const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
if (!ms || !station) return
try {
if (MEDIA_METADATA) {
ms.metadata = new MEDIA_METADATA({
title: now?.title || station.name || '',
artist: now?.artist || station.genre || station.detail || '',
album: 'KuentaGYM Radio',
artwork: station.image || now?.cover
? [{ src: (station.image || now?.cover), sizes: '512x512', type: 'image/jpeg' }]
: []
})
}
// The handlers are how the lock screen's buttons reach this element.
ms.setActionHandler?.('play', () => playStream(audio?.src))
ms.setActionHandler?.('pause', () => pauseStream())
ms.setActionHandler?.('stop', () => pauseStream())
} catch { /* a browser without Media Session simply shows nothing */ }
}
export function clearMediaSession() {
const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
if (!ms) return
try {
ms.metadata = null
ms.setActionHandler?.('play', null)
ms.setActionHandler?.('pause', null)
ms.setActionHandler?.('stop', null)
} catch { /* as above */ }
}
/** Only for tests: forget the element so each one starts clean. */
export function __resetRadioAudio() { audio = null }
+22
View File
@@ -1408,6 +1408,28 @@ export default {
// segunda opinión (Jev)
'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
'Podcasts': 'Podcasts',
'Podcast': 'Podcast',
'Saved podcasts': 'Podcasts guardados',
'Save this podcast': 'Guardar este podcast',
'Saved to your podcasts': 'Guardado en tus podcasts',
'Open {0}': 'Abrir {0}',
'Loading podcasts…': 'Cargando podcasts…',
'Reading the feed…': 'Leyendo el feed…',
'No Spanish shows come back for this category. Try another one.': 'No volvió ningún programa en español para esta categoría. Probá con otra.',
'No Spanish shows came back for this category. Try another one.': 'No volvió ningún programa en español para esta categoría. Probá con otra.',
'That feed did not answer. It may be down, or it may block this server.': 'Ese feed no respondió. Puede estar caído, o bloquear a este servidor.',
'That podcast is not in Spanish, so it is not listed here.': 'Ese podcast no está en español, así que no se lista acá.',
'That feed has no playable episodes in it — trailers only, or subscriber-only audio.': 'Ese feed no tiene episodios que se puedan reproducir: sólo avances, o audio sólo para suscriptores.',
'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.': 'Sólo podcasts en español, y eso se comprueba en el feed de cada programa en vez de darlo por hecho por la tienda. No se descarga nada: el episodio va directo de quien lo publica a tu teléfono, y lo que ya escuchaste queda guardado por perfil.',
'Your server has not been updated for the podcasts yet: it is the server that finds them, and this app is newer than it. Restarting it should be enough.': 'Tu servidor todavía no se actualizó para los podcasts: los busca el servidor, y esta app es más nueva que él. Reiniciarlo debería alcanzar.',
'Podcasts come from your server, so they need a profile: sign in and the shows appear here.': 'Los podcasts vienen de tu servidor, así que necesitan un perfil: entrá a tu cuenta y los programas aparecen acá.',
'15 seconds back': '15 segundos atrás',
'30 seconds forward': '30 segundos adelante',
'Next episode': 'Siguiente episodio',
'Heard': 'Escuchado',
'{0} in': 'en {0}',
// radio
'Radio': 'Radio',
'Playing {0}': 'Sonando {0}',
+41
View File
@@ -11,6 +11,7 @@ import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js
import { loadCoachDevice, saveCoachDevice, coachDeviceSettings } from '../lib/coach-device.js'
import { WC_DEFAULT } from '../lib/workout-controls.js'
import { trimProgress } from '../lib/podcast-view.js'
const KEY = 'gym_state_v1'
// Where this device stands with the server: the revision it last adopted or pushed, and its own
@@ -36,6 +37,10 @@ export const DEF = {
// are the share links the Music app copies, with whatever the public page could tell us about
// them. In the profile document like the routines, so they sync and they are backed up.
music: { user: '', playlists: [], stations: [] },
// Podcasts: the shows saved next to the radio stations, and where each episode was left off.
// The positions are the whole reason this is in the profile document rather than in memory — a
// 50-minute episode resumed from the beginning on the next device is the feature not working.
podcasts: { shows: [], progress: {} },
// How the active workout is laid out — 'cards' (one exercise at a time with Prev/Next),
// 'list' (every exercise stacked and scrollable) or 'compact' (that stack stripped to just
// names and set rows — no media, tags, notes, last-time or progression line). Purely
@@ -373,6 +378,42 @@ export const useStore = create((set, get) => {
})
},
/* Podcast shows, keyed by their feed: the same show reached from two categories is one row, and
unstarring one never depends on its position. */
addPodcast(show) {
if (!show || !show.feed) return
get().update(s => {
const pod = s.podcasts || { shows: [], progress: {} }
const list = pod.shows || []
if (list.some(x => x.feed === show.feed)) return
s.podcasts = {
...pod,
shows: [...list, {
feed: show.feed, name: show.name || '', author: show.author || '',
image: show.image || null, genre: show.genre || '', lang: show.lang || null
}]
}
})
},
removePodcast(feed) {
get().update(s => {
const pod = s.podcasts || { shows: [], progress: {} }
s.podcasts = { ...pod, shows: (pod.shows || []).filter(x => x.feed !== feed) }
})
},
/* Where an episode was left off. Called on the player's own schedule (not on every tick), and
trimmed: two hundred episodes is years of listening, and an unbounded map in a document that
syncs to the server is a slow leak nobody would ever notice. */
savePodcastPosition(episodeId, position, duration) {
if (!episodeId || !Number.isFinite(Number(position))) return
get().update(s => {
const pod = s.podcasts || { shows: [], progress: {} }
const progress = { ...(pod.progress || {}) }
progress[episodeId] = { pos: Math.max(0, Math.round(Number(position))), dur: Math.round(Number(duration) || 0) || null, at: Date.now() }
s.podcasts = { ...pod, progress: trimProgress(progress) }
})
},
/* Apple Music playlists (views/Music.jsx). Two mutations rather than one generic setter,
because the list is keyed by the playlist id: adding the same link twice is a no-op rather
than two identical cards, and removing one never depends on its position. */
@@ -0,0 +1,91 @@
// @vitest-environment happy-dom
/* The shows a profile saves, and where each episode was left off.
*
* The positions are the reason this state is in the profile document instead of in memory: resume a
* 50-minute episode from the beginning on the next device and the feature simply does not exist. Two
* things have to hold, and neither is visible from the screen:
*
* - A position is *merged*, never rebuilt. `podcasts` holds the shows and the positions, and the
* methods that touch one must leave the other alone — the same bug the radio stations had, where
* removing a playlist wiped them.
* - It is *bounded*. Two hundred episodes is years of listening; an unbounded map in a document
* that syncs to the server is a leak nobody would ever notice. */
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../lib/api.js', () => ({ api: vi.fn().mockResolvedValue({}) }))
import { useStore } from './useStore.js'
import { MAX_PROGRESS } from '../lib/podcast-view.js'
const show = (over = {}) => ({ feed: 'https://a.example.com/feed', name: 'Nadie Sabe Nada', author: 'Cadena SER', genre: 'Comedy', image: 'https://x/a.jpg', ...over })
const pod = () => useStore.getState().S.podcasts
beforeEach(() => {
useStore.setState(s => ({ S: { ...s.S, podcasts: { shows: [], progress: {} } } }))
})
describe('saved podcasts', () => {
it('saves a show by its feed, and the same feed twice is one row', () => {
useStore.getState().addPodcast(show())
useStore.getState().addPodcast(show({ name: 'Nadie Sabe Nada (otra vez)' }))
expect(pod().shows).toHaveLength(1)
expect(pod().shows[0].name).toBe('Nadie Sabe Nada')
})
it('refuses a show with no feed, which could never be opened again', () => {
useStore.getState().addPodcast(show({ feed: null }))
useStore.getState().addPodcast(null)
expect(pod().shows).toHaveLength(0)
})
it('unsaves the one it was asked about, and only that one', () => {
useStore.getState().addPodcast(show())
useStore.getState().addPodcast(show({ feed: 'https://b.example.com/feed', name: 'Otro' }))
useStore.getState().removePodcast('https://a.example.com/feed')
expect(pod().shows.map(s => s.name)).toEqual(['Otro'])
})
it('survives a state that predates podcasts', () => {
useStore.setState(s => ({ S: { ...s.S, podcasts: undefined } }))
useStore.getState().addPodcast(show())
expect(pod().shows).toHaveLength(1)
expect(pod().progress).toEqual({})
})
})
describe('where an episode was left off', () => {
it('writes a position with its length and a timestamp', () => {
useStore.getState().savePodcastPosition('ep-1', 620.7, 3135.4)
const entry = pod().progress['ep-1']
expect(entry.pos).toBe(621)
expect(entry.dur).toBe(3135)
expect(entry.at).toBeGreaterThan(0)
})
it('refuses a position that is not a number', () => {
useStore.getState().savePodcastPosition('ep-1', Number.NaN, 100)
useStore.getState().savePodcastPosition('ep-2', 'mucho', 100)
useStore.getState().savePodcastPosition(null, 10, 100)
expect(pod().progress).toEqual({})
})
it('keeps the newest positions and forgets the oldest', () => {
for (let i = 0; i < MAX_PROGRESS + 10; i++) useStore.getState().savePodcastPosition('ep-' + i, 100, 3600)
const kept = pod().progress
expect(Object.keys(kept).length).toBe(MAX_PROGRESS)
expect(kept['ep-' + (MAX_PROGRESS + 9)]).toBeTruthy()
expect(kept['ep-0']).toBeUndefined()
})
it('is not dropped by the mutations that share `podcasts`', () => {
useStore.getState().addPodcast(show())
useStore.getState().savePodcastPosition('ep-1', 600, 3135)
useStore.getState().savePodcastPosition('ep-2', 60, 3135)
useStore.getState().removePodcast('https://a.example.com/feed')
expect(pod().shows).toHaveLength(0)
expect(Object.keys(pod().progress)).toEqual(['ep-1', 'ep-2'])
useStore.getState().addPodcast(show())
expect(Object.keys(pod().progress)).toEqual(['ep-1', 'ep-2'])
})
})
+188 -7
View File
@@ -2,7 +2,12 @@ import { create } from 'zustand'
import { uid } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { api } from '../lib/api.js'
import { playStream, pauseStream, setStreamVolume, setMediaSession, clearMediaSession } from '../lib/radio-player.js'
import {
playStream, playFile, pausePlayer, resumePlayer, seekBy, setPlayerVolume,
setStreamSession, setEpisodeSession, setSessionPosition, wireSessionHandlers,
clearSession, playerTime, onPlayer
} from '../lib/player.js'
import { resumeSeconds, nextEpisode, prevEpisode, queueFor, worthSaving } from '../lib/podcast-view.js'
import { t } from '../lib/i18n.js'
import { deviceId } from '../lib/push.js'
import { useStore } from './useStore.js'
@@ -26,6 +31,53 @@ if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => { if (document.hidden) pageHiddenAt = Date.now() })
}
/* ---------- the podcast's own bookkeeping, at module scope ----------
*
* How often an episode's position reaches the profile. Not on every `timeupdate` — that is four
* times a second, and the document syncs to the server — but every few seconds, and always at the
* moments where losing it would hurt: pausing, stopping, the end of an episode, and the app going
* to the background (the last tick before a locked screen is the last one for a while: iOS
* suspends these timers, so if the position were saved only from a tick, locking the phone would
* lose up to five seconds of listening — and, worse, anything at all if the tab were killed). */
const POD_SAVE_MS = 5000;
let podSavedAt = 0;
/** Write the current position into the profile, if it is worth writing and the moment is right. */
function savePodPosition(force = false) {
const { pod } = useUI.getState();
if (!pod?.episode) return;
const { position, duration } = playerTime();
const pos = Number.isFinite(position) ? position : pod.position;
const dur = Number.isFinite(duration) && duration > 0 ? duration : pod.duration;
if (!worthSaving({ pos }, dur)) return;
const now = Date.now();
if (!force && now - podSavedAt < POD_SAVE_MS) return;
podSavedAt = now;
useStore.getState().savePodcastPosition(pod.episode.id, pos, dur || 0);
}
if (typeof document !== 'undefined') {
// `pagehide` and the hidden state, because neither is a promise to come back: a phone that locks
// while an episode plays is the normal case here, not the edge case.
document.addEventListener('visibilitychange', () => { if (document.hidden) savePodPosition(true) });
window.addEventListener('pagehide', () => savePodPosition(true));
}
/* The player reports; the store decides. Registered once, at import, so the bar and the profile keep
up whether or not any component happens to be mounted — which matters, because the whole point of
the bar living above the router is that the music outlives the screen it started on. */
onPlayer((event, state) => {
const ui = useUI.getState();
if (!ui.pod) return;
if (event === 'time') { ui.setPodPlayback({ position: state.position, duration: state.duration }); return }
if (event === 'meta') { setSessionPosition(state.duration, state.position); ui.setPodPlayback({ duration: state.duration }); return }
if (event === 'playing') { ui.setPodPlayback({ playing: true }); return }
if (event === 'paused') { ui.setPodPlayback({ playing: false }); savePodPosition(true); return }
if (event === 'ended') { ui.podEnded(); return }
// A dead file is not a wrong tap: the bar says it stopped rather than claiming it is playing.
if (event === 'error') { ui.setPodPlayback({ playing: false }); savePodPosition(true) }
});
// The Push switch in Settings is the one place notifications are turned on, and "on" means this
// browser holds a push subscription. This local alert used to ignore it: every rest asked for the
// permission by itself, and once granted — a page cannot hand a permission back — it fired with the
@@ -64,7 +116,8 @@ export const useUI = create((set, get) => ({
sheets: [], // { id, render:(close)=>JSX, kind:'sheet'|'center', locked }
toastMsg: '',
timer: null, // rest countdown between sets — { left, total, endsAt, forIdx }
radio: null, // { station, playing, volume, now } — the audio element lives in lib/radio-player.js
radio: null, // { station, playing, volume, now } — the audio element lives in lib/player.js
pod: null, // { show, episode, queue, playing, position, duration } — same element, a file
// forIdx: index of the active entry whose set started the rest (undefined when unknown)
work: null, // work countdown DURING a timed set (issue #16) — { left, total, endsAt, label }
timerFlashId: 0, // changing the id retriggers the theme-blink visual alert
@@ -90,26 +143,154 @@ export const useUI = create((set, get) => ({
},
/* Radio. The stream URL arrives with the station, so this is synchronous from the press to the
`play()` — which is the whole reason iOS lets it start at all. Nothing here fetches. */
`play()` — which is the whole reason iOS lets it start at all. Nothing here fetches, and
nothing here waits: the one thing that would break it is an `await` before the play. */
playRadio(station, { volume } = {}) {
if (!station || !station.url) return false
// One element, two kinds of media: starting a station ends the episode, and vice versa.
get().stopPod()
const v = volume != null ? volume : (get().radio?.volume ?? 1)
const ok = playStream(station.url, v)
set({ radio: { station, playing: ok, volume: v, now: null } })
setMediaSession(station, null)
setStreamSession(station, null)
wireSessionHandlers()
return ok
},
toggleRadio() {
const r = get().radio
if (!r) return
if (r.playing) { pauseStream(); set({ radio: { ...r, playing: false } }) }
if (r.playing) { pausePlayer(); set({ radio: { ...r, playing: false } }) }
else { const ok = playStream(r.station.url, r.volume); set({ radio: { ...r, playing: ok } }) }
},
stopRadio() {
pauseStream()
clearMediaSession()
pausePlayer()
clearSession()
set({ radio: null })
},
/* Volume, for whoever puts a slider on screen. Nothing draws one today, and there is a reason to
think before drawing one: **iOS ignores `HTMLMediaElement.volume` entirely** — the hardware
buttons are the only volume there — so a slider on an iPhone would be a control that does
nothing. It works on Android and desktop, where the element's volume is real. */
setRadioVolume(volume) {
const r = get().radio
setPlayerVolume(volume)
if (r) set({ radio: { ...r, volume } })
},
/* What the station says it is playing. Only SomaFM and Radio Paradise publish it, and the
lock screen gets it too — that is what makes the phone in a pocket show the track. */
setRadioNow(now) {
const r = get().radio
if (!r) return
set({ radio: { ...r, now } })
setStreamSession(r.station, now)
},
/* ---------- podcasts: the same element, but a file ----------
*
* Where a stream is one command and done, an episode has state that has to be remembered: the
* position, what to play when it ends, and where you were the next time you open it. All of that
* lives here, and every write to the profile is throttled — a position is saved on the player's
* schedule and when the app goes to the background, never on every tick, because the document
* syncs to the server and a tick is four times a second. */
/** Play an episode, resuming where it was left off. Synchronous, for the reason above. */
playEpisode(show, episode, queue) {
if (!episode || !episode.url) return false
get().stopRadio()
const saved = useStore.getState().S.podcasts?.progress?.[episode.id]
const startAt = resumeSeconds(saved, episode.duration)
const ok = playFile(episode.url, { startAt })
set({
pod: {
show: show || null,
episode,
queue: queueFor(queue, episode),
playing: ok,
position: startAt,
duration: Number(episode.duration) || null
}
})
setEpisodeSession(show, episode)
wireSessionHandlers()
savePodPosition(true)
return ok
},
togglePod() {
const p = get().pod
if (!p) return
if (p.playing) {
pausePlayer()
set({ pod: { ...p, playing: false } })
savePodPosition(true)
} else {
const ok = playFile(p.episode.url, { startAt: p.position || 0 })
set({ pod: { ...p, playing: ok } })
}
},
stopPod() {
if (!get().pod) return
pausePlayer()
savePodPosition(true)
clearSession()
set({ pod: null })
},
/** Fifteen seconds back, thirty forward — the two buttons a podcast is actually driven with. */
podSeek(seconds) {
const p = get().pod
if (!p) return
const to = seekBy(seconds)
if (to == null) return
set({ pod: { ...p, position: to } })
setSessionPosition()
},
podNext() {
const p = get().pod
if (!p) return false
const next = nextEpisode(p.queue, p.episode.id)
// The end of the queue is the end: no wrapping back to the start, which is a surprise nobody
// wants in the middle of a workout.
if (!next) return false
return get().playEpisode(p.show, next, p.queue)
},
podPrev() {
const p = get().pod
if (!p) return false
const prev = prevEpisode(p.queue, p.episode.id)
if (!prev) return false
return get().playEpisode(p.show, prev, p.queue)
},
/** Called by the player's own events: the position on screen, and sometimes the profile.
*
* The position is only written to the store when the whole second changed. `timeupdate` fires
* about four times a second, and four renders a second for a clock that shows seconds is work
* nobody can see — while the *saved* position is on its own, slower schedule again. */
setPodPlayback({ position, duration, playing } = {}) {
const p = get().pod
if (!p) return
const sameSecond = !Number.isFinite(position) || Math.floor(position) === Math.floor(p.position || 0)
const sameDuration = !Number.isFinite(duration) || duration <= 0 || duration === p.duration
const samePlaying = playing == null || playing === p.playing
if (sameSecond && sameDuration && samePlaying) return
set({
pod: {
...p,
position: Number.isFinite(position) ? position : p.position,
duration: Number.isFinite(duration) && duration > 0 ? duration : p.duration,
playing: playing == null ? p.playing : playing
}
})
savePodPosition(false)
},
/** Mark this episode heard and start the next one, or stop at the end of the queue. */
podEnded() {
const p = get().pod
if (!p) return
const { position, duration } = playerTime()
useStore.getState().savePodcastPosition(p.episode.id, duration || p.duration || 0, duration || p.duration)
if (get().podNext()) return
pausePlayer()
set({ pod: { ...p, playing: false, position: Number.isFinite(duration) ? duration : p.position } })
},
/* Volume, for whoever puts a slider on screen. Nothing draws one today, and there is a reason to
think before drawing one: **iOS ignores `HTMLMediaElement.volume` entirely** — the hardware
buttons are the only volume there — so a slider on an iPhone would be a control that does
+159 -1
View File
@@ -26,6 +26,7 @@ import { confirmSheet } from '../sheets.jsx'
import { Button } 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'
/** A playlist tile: artwork when the public page gave us some, a note when it did not. */
function PlaylistCard({ item, onRemove }) {
@@ -91,7 +92,7 @@ function AddPlaylistSheet({ close }) {
* Live stations, not files: a public stream is made to be listened to, so nothing is downloaded and
* the audio goes from the station straight to the phone. What this screen does is the list — which
* genres, which stations, what is playing — and the play button hands the stream to the single audio
* element in lib/radio-player.js.
* element in lib/player.js — the one element it shares with the podcasts.
*
* The stations with no advertising at all come first in every genre, because that is a property
* worth ranking: SomaFM and Radio Paradise are listener-supported by mission, and the directory's
@@ -195,6 +196,161 @@ function RadioSection() {
</>
}
/* ---------- podcasts ----------
*
* Spanish-language shows, by category, from Apple's directory (free, no key), with the episodes read
* out of the publisher's own feed — the long version is in api/podcasts.js, which owns the two rules
* that matter: **nothing but Spanish**, checked in the feed itself rather than trusted from the
* storefront, and **nothing fetched from a private address**, because this container lives inside
* somebody's house.
*
* The audio never passes through the server: an episode is an `https://` file URL, handed to the one
* 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() {
const user = useStore(s => s.user)
const cfg = useStore(s => s.config)
const S = useStore(s => s.S)
const addPodcast = useStore(s => s.addPodcast)
const removePodcast = useStore(s => s.removePodcast)
const progress = (S.podcasts && S.podcasts.progress) || {}
const openSheet = useUI(s => s.openSheet)
const toast = useUI(s => s.toast)
const [categories, setCategories] = useState(null)
const [category, setCategory] = useState(null)
const [shows, setShows] = useState(null)
const [busy, setBusy] = useState(false)
const [noArt, setNoArt] = useState(() => new Set())
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.
const staleApi = !!cfg && Array.isArray(cfg.features) && !cfg.features.includes('podcasts')
const canPodcasts = !!user && !staleApi
const load = key => {
setBusy(true)
api('/api/podcasts' + (key ? '?category=' + encodeURIComponent(key) : ''))
.then(r => {
setCategories(r.categories)
setCategory(r.category)
setShows(r.shows)
})
.catch(e => toast(e.message))
.finally(() => setBusy(false))
}
useEffect(() => { if (canPodcasts) load(null) }, [canPodcasts])
const isSaved = show => saved.some(x => x.feed === show.feed)
const row = show => <div key={show.feed} className="mus-rad">
<button className="mus-rad-main" onClick={() => openSheet(close => <ShowSheet show={show} close={close} progress={progress} />)} aria-label={t('Open {0}', show.name)}>
{show.image && !noArt.has(show.image)
? <img className="mus-rad-i" src={show.image} alt="" onError={() => setNoArt(prev => new Set(prev).add(show.image))} />
: <span className="mus-rad-i mus-rad-i-ph"><Icon name="music" /></span>}
<span className="mus-rad-meta">
<span className="mus-rad-n">{show.name}</span>
<span className="mus-rad-s">{[show.author, show.genre].filter(Boolean).join(' · ')}</span>
</span>
<Icon name="chevronRight" className="mus-rad-go" />
</button>
<button className="iconbtn mus-rad-save" aria-label={isSaved(show) ? t('Remove') : t('Save this podcast')}
onClick={() => isSaved(show) ? removePodcast(show.feed) : (addPodcast(show), toast(t('Saved to your podcasts')))}>
<Icon name={isSaved(show) ? 'starFill' : 'star'} />
</button>
</div>
return <>
<h4 className="sec">{t('Podcasts')}</h4>
{!canPodcasts
? <div className="small dim" style={{ margin: '0 2px 8px', lineHeight: 1.45 }}>
{staleApi
? t('Your server has not been updated for the podcasts yet: it is the server that finds them, and this app is newer than it. Restarting it should be enough.')
: 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 }}>
{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 }}>
{(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 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.')}
</div>}
</>}
</>
}
/* The episodes of one show, in a sheet: tap one and it plays. The list comes from the feed, newest
first, and every row says where you are in it. */
function ShowSheet({ show, close, progress }) {
const playEpisode = useUI(s => s.playEpisode)
const [data, setData] = useState(null)
const [err, setErr] = useState('')
useEffect(() => {
let live = true
const q = new URLSearchParams({ feed: show.feed })
if (show.name) q.set('title', show.name)
if (show.image) q.set('image', show.image)
api('/api/podcasts/show?' + q.toString())
.then(r => {
if (!live) return
if (!r.show) { setErr(t('That feed did not answer. It may be down, or it may block this server.')); return }
if (r.spanish === false) { setErr(t('That podcast is not in Spanish, so it is not listed here.')); return }
setData(r)
})
.catch(e => { if (live) setErr(e.message) })
return () => { live = false }
}, [show.feed])
const play = ep => {
// Synchronous on purpose: the `play()` has to happen inside this tap for iOS to allow it.
playEpisode({ ...(data?.show || {}), name: show.name, image: show.image }, ep, data?.episodes || [])
close()
}
return <div className="pod-sheet">
<div className="pod-head">
{show.image
? <img className="pod-head-i" src={show.image} alt="" />
: <span className="pod-head-i plr-cover-ph"><Icon name="music" /></span>}
<div>
<div className="pod-head-n">{show.name}</div>
{show.author && <div className="small dim">{show.author}</div>}
</div>
</div>
{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)}>
<Icon name="play" className="pod-ep-i" />
<span className="pod-ep-meta">
<span className="pod-ep-t">{ep.title}</span>
<span className="pod-ep-s">
{episodeMeta(ep)}
{progress[ep.id] ? <span className="pod-heard"> · {isFinished(progress[ep.id], ep.duration)
? t('Heard')
: t('{0} in', fmtClock(resumeSeconds(progress[ep.id], ep.duration)))}</span> : null}
</span>
</span>
</button>)}
</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.')}
</div>}
</div>
}
export default function Music() {
const nav = useNavigate()
const S = useStore(s => s.S)
@@ -241,6 +397,8 @@ export default function Music() {
<RadioSection />
<PodcastSection />
<h4 className="sec">{t('Playlists')}</h4>
{list.length === 0
? <div className="empty">
+113 -7
View File
@@ -14,15 +14,27 @@ vi.mock('react-router-dom', () => ({ useNavigate: () => nav }))
vi.mock('../sheets.jsx', () => ({ confirmSheet: vi.fn() }))
const api = vi.fn()
vi.mock('../lib/api.js', async importOriginal => ({ ...(await importOriginal()), api: (...a) => api(...a) }))
/* The audio element lives in lib/radio-player.js, outside React; the radio section reaches it
through the store. Mocked so a test can assert *when* it was asked to play — see the row test. */
/* The audio element lives in lib/player.js, outside React; both sections reach it through the store.
Mocked so a test can assert *when* it was asked to play — see the station row test. `onPlayer` is
called once at module scope (the store listens from import), so it has to exist and answer with an
unsubscribe. */
const playStream = vi.fn(() => true)
vi.mock('../lib/radio-player.js', () => ({
const playFile = vi.fn(() => true)
vi.mock('../lib/player.js', () => ({
playStream: (...a) => playStream(...a),
pauseStream: vi.fn(),
setStreamVolume: vi.fn(),
setMediaSession: vi.fn(),
clearMediaSession: vi.fn()
playFile: (...a) => playFile(...a),
pausePlayer: vi.fn(),
resumePlayer: vi.fn(() => true),
seekBy: vi.fn(() => 0),
seekTo: vi.fn(() => 0),
playerTime: () => ({ position: 0, duration: null }),
setPlayerVolume: vi.fn(),
setStreamSession: vi.fn(),
setEpisodeSession: vi.fn(),
setSessionPosition: vi.fn(),
wireSessionHandlers: vi.fn(),
clearSession: vi.fn(),
onPlayer: () => () => {}
}))
const { default: Music } = await import('./Music.jsx')
@@ -40,6 +52,7 @@ beforeEach(() => {
api.mockReset()
api.mockResolvedValue({ genres: [], genre: null, stations: [] })
playStream.mockClear()
playFile.mockClear()
act(() => { useUI.setState({ radio: null }) })
host = document.createElement('div')
document.body.appendChild(host)
@@ -54,6 +67,17 @@ beforeEach(() => {
})
afterEach(() => { act(() => root.unmount()); host.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
sections fight over one object. */
const stubApi = ({ radio = { genres: [], genre: null, stations: [] }, podcasts = { categories: [], category: null, shows: [] }, show = { show: null, episodes: [], error: 'unreadable' } } = {}) =>
api.mockImplementation(path => {
if (String(path).startsWith('/api/radio')) return Promise.resolve(radio)
if (String(path).startsWith('/api/podcasts/show')) return Promise.resolve(show)
if (String(path).startsWith('/api/podcasts')) return Promise.resolve(podcasts)
return Promise.resolve({ ok: true })
})
const mount = async () => { await act(async () => { root.render(<Music />) }) }
const links = () => [...host.querySelectorAll('a')]
@@ -191,4 +215,86 @@ describe('Música', () => {
expect(host.querySelectorAll('.mus-card').length).toBe(1)
expect(host.textContent).toContain('Leg Day')
})
/* ---------- podcasts ---------- */
const category = { key: 'fitness', label: 'Salud y fitness' }
const cat = { key: 'fitness', label: 'Salud y fitness' }
const showRow = (over = {}) => ({ feed: 'https://a.example.com/feed', name: 'Tiene Sentido', author: 'Eli Romero', genre: 'Health & Fitness', image: null, lang: 'es', ...over })
const ep = (over = {}) => ({ id: 'ep-1', title: 'Experta en Inflamación', url: 'https://audio.example.com/1.mp3', date: '2025-09-21T10:00:00.000Z', duration: 3600, image: null, ...over })
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()
const chips = [...host.querySelectorAll('.chips .chip')]
expect(chips.map(c => c.textContent)).toContain('Salud y fitness')
const rows = [...host.querySelectorAll('.mus-rad')]
const show = rows[rows.length - 1]
expect(show.textContent).toContain('Tiene Sentido')
expect(show.textContent).toContain('Eli Romero · Health & Fitness')
expect(api).toHaveBeenCalledWith('/api/podcasts')
})
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()
const star = [...host.querySelectorAll('.mus-rad-save')].pop()
act(() => { star.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useStore.getState().S.podcasts.shows.map(s => s.feed)).toEqual(['https://a.example.com/feed'])
expect(host.textContent).toContain('Saved podcasts')
})
it('opens a show into its episodes, and plays one — resuming where it was left off', async () => {
const one = ep()
stubApi({
podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] },
show: { feed: 'https://a.example.com/feed', spanish: true, show: { title: 'Tiene Sentido', author: 'Eli', language: 'es' }, episodes: [one, ep({ id: 'ep-2', title: 'Otro' })] }
})
// 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 /></>) })
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 eps = [...document.querySelectorAll('#modal-root .pod-ep')]
expect(eps.map(e => e.textContent)).toHaveLength(2)
expect(eps[0].textContent).toContain('Experta en Inflamación')
// Already ten minutes into it, from wherever it was left off — the tests run on the English keys.
expect(eps[0].textContent).toContain('10:00 in')
act(() => { eps[0].dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(playFile).toHaveBeenCalledWith('https://audio.example.com/1.mp3', { startAt: 600 })
expect(useUI.getState().pod.episode.id).toBe('ep-1')
expect(useUI.getState().pod.queue).toHaveLength(2)
})
it('says so when a feed is not in Spanish, instead of showing an empty episode list', async () => {
stubApi({
podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] },
show: { feed: 'https://a.example.com/feed', spanish: false, show: { title: 'English Show', language: 'en' }, episodes: [] }
})
await act(async () => { root.render(<><Music /><Modals /></>) })
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() })
expect(document.querySelector('#modal-root').textContent).toContain('not in Spanish')
})
it('tells a guest where the podcasts come from, without asking the server', async () => {
useStore.setState({ user: null })
await mount()
expect(host.textContent).toContain('Podcasts come from your server, so they need a profile')
expect(api).not.toHaveBeenCalled()
})
it('says the server is older when it does not offer podcasts yet', async () => {
useStore.setState({ config: { features: ['vitals', 'radio'] } })
await mount()
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)
})
})