El reproductor completo al tocar la barra, y el episodio siguiente al terminar
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

Tocar la barra abre el reproductor completo, como el de Spotify: portada en grande,
título entero, programa, autor, número de episodio y fecha, una barra que se arrastra,
el tiempo transcurrido y **lo que falta**, −15/+30, anterior y siguiente, y una línea
que dice **"Después: …"** con el nombre del que sigue —o que es el último de la lista.
Es una hoja, no una ruta, por lo mismo de siempre: una pantalla dentro del router se
desmonta al navegar y esto no puede ser lo que corte el audio. Para una emisora el
mismo reproductor no dibuja barra de progreso: una radio en vivo no tiene posición ni
final, y decirlo es mejor que un slider muerto.

Un episodio que termina **sigue con el siguiente** de la lista en la que lo pusiste a
sonar, sin tocar el teléfono; al final de la lista se detiene y el reproductor lo
avisa antes. El que termina queda marcado como escuchado. Los botones de siguiente y
anterior de la **pantalla bloqueada** ahora llegan al elemento de audio, que es donde
alguien con las manos en la barra los va a apretar.

Y dos cosas que aparecieron revisando esto:

- `setRadioNow` llamaba a `setMediaSession`, una función que ya no existe desde que el
  reproductor se unificó (hoy `setStreamSession`). El error quedaba **tragado** por el
  `.catch` del sondeo: la pantalla mostraba el tema —el estado se actualiza antes de la
  línea que falla— y la **pantalla bloqueada nunca se enteraba** del tema que sonaba.
  Ahora hay un test que lo mira y se comprobó por mutación.
- `useUI` tenía **dos definiciones** de `setRadioVolume` y `setRadioNow`: al insertar el
  bloque de podcasts había quedado duplicado el final del bloque de radio, y en un
  objeto literal la última gana en silencio. Una copia era código muerto que se leía
  como vivo — y fue la que hizo que el primer intento de comprobar lo anterior "pasara".

Tests nuevos: useUI.podcast.test.js (16, con el reproductor burlado emitiendo lo que
emite un navegador: ended → siguiente, time → reloj, paused → posición guardada),
NowPlaying.test.jsx (13) y el toque en la barra en PlayerBar.test.jsx.
This commit is contained in:
dsantillan committed 2026-09-23 21:40:17 -04:00
1 parent d5cf0d8d64
commit 78b815ae8f
14 files changed
+754 -38

No files matched your search

+33
View File
@@ -1,5 +1,38 @@
# Changelog
## Sin publicar — El reproductor completo, y lo que sigue después
Tocar la barra del reproductor **abre el reproductor completo**, como el de Spotify: la portada en
grande, el título del episodio entero en vez de recortado, el programa, el autor, el número de
episodio y la fecha, una **barra que se arrastra** (el slider de la casa, con `data-nodrag` para que
un arrastre lateral no se lea como cerrar la hoja), el tiempo transcurrido y **lo que falta** —que es
el número con el que se decide si da para otro episodio—, −15 / +30, anterior y siguiente, y
**"Después: …"** con el nombre del que sigue. Es una *hoja*, no una ruta: una pantalla dentro del
router se desmonta al navegar, y esto no puede ser nunca lo que corte el audio. Se cierra
deslizando hacia abajo, con el gesto de siempre, o con el botón de atrás de Android.
Para una **emisora** el mismo reproductor muestra el logo, el nombre, el género y qué está sonando
—o que esa emisora no publica lo que suena— y **no dibuja barra de progreso**: una radio en vivo no
tiene posición ni final, y decirlo es mejor que un slider muerto.
**Cuando un episodio termina, sigue el siguiente** de la lista en la que lo pusiste a sonar, sin
tocar el teléfono; al final de esa lista se detiene y el reproductor completo lo avisa antes
("Es el último episodio de esta lista"). El que terminó queda marcado como escuchado antes de pasar
al otro. Lo mismo está en la **pantalla bloqueada**: los botones de siguiente y anterior ahora
llegan al elemento de audio, que es donde alguien con las manos en la barra los va a apretar.
Dos cosas que aparecieron revisando esto, y que valen más que la función:
- `setRadioNow` llamaba a una función que ya no existía desde que el reproductor se unificó
(`setMediaSession`, hoy `setStreamSession`). El error quedaba **tragado** por el `.catch` del
sondeo: la pantalla mostraba el tema —el estado se actualizaba antes de la línea que fallaba— y la
**pantalla bloqueada nunca se enteraba**. Un fallo invisible que sólo se ve comparando lo que dice
el teléfono con lo que dice la app; ahora hay un test que lo mira, y se comprobó por mutación.
- `useUI` tenía **dos definiciones** de `setRadioVolume` y `setRadioNow`: al insertar el bloque de
podcasts quedó el final del bloque de radio duplicado, y en un objeto literal la última gana en
silencio. Una de las dos copias era código muerto que se leía como vivo — y fue justamente la que
hizo que el primer intento de comprobar lo anterior "pasara".
## Sin publicar — Música se ordena: pestañas, buscador y listas de diez
La pantalla de Música era una sola columna: la radio, después los podcasts, después las listas.
+1 -1
View File
@@ -95,7 +95,7 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
- 🌍 **14 languages** — full UI translation (EN, DE, ES, FR, IT, PT (Portugal), PT (Brazil), PL, TR, RU, ZH, KO, HI, TH, HU); exercise instructions localized in 12 of them and built-in exercise names shown bilingually in PT-BR and HU, all loaded on demand so the app stays fast
- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy** (CSV or directly with a [Hevy Pro API key](https://hevy.com/settings?developer)), or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped
- 📻 **Radio while you train** — a **Radio** section in Música: live stations by genre (workout/rave, techno, R&B, Latin, hip-hop, reggae, chill, jazz, rock, electronic), the ad-free ones first — SomaFM and Radio Paradise — then the public [radio-browser](https://www.radio-browser.info) directory. It keeps playing across screens, with the screen locked and the phone in your pocket, and the lock screen shows the station and the track. **The audio goes straight from the station to your phone** — your server hands out the list and never proxies or stores a byte of it, and nothing is downloaded. No new dependencies. See [docs/RADIO.md](docs/RADIO.md)
- 🎙️ **Podcasts while you train** — a **Podcasts** section in Música: shows by category (health and fitness, sport, comedy, news, history, true crime, science, tech, society, business, fiction, education, music, leisure) from Apple's public directory, **in Spanish only** — and that is checked in each show's own feed, not assumed from the storefront it was found in. An episode is a file, so it resumes where you left off, marks itself heard, seeks back 15 s and forward 30 s, and plays the next one when it ends; the lock screen shows the episode and how far in you are. **Nothing is downloaded and no audio passes through your server** — the feed says where the file is and the phone goes and gets it. No new dependencies. See [docs/PODCASTS.md](docs/PODCASTS.md)
- 🎙️ **Podcasts while you train** — a **Podcasts** section in Música: shows by category (health and fitness, sport, comedy, news, history, true crime, science, tech, society, business, fiction, education, music, leisure) from Apple's public directory, **in Spanish only** — and that is checked in each show's own feed, not assumed from the storefront it was found in. An episode is a file, so it resumes where you left off, marks itself heard, seeks back 15 s and forward 30 s, and **continues with the next one when it ends**; tapping the bar opens the **full player** (artwork at size, a draggable scrubber, what is left, and what plays next), and the lock screen shows the episode, its progress, and its next/previous buttons. **Nothing is downloaded and no audio passes through your server** — the feed says where the file is and the phone goes and gets it. No new dependencies. See [docs/PODCASTS.md](docs/PODCASTS.md)
- ❤️ **Salud: your Apple Health, live** — a **Salud** screen (the heart button in Home's header) draws whatever your iPhone reports: steps, heart rate, sleep, weight, oxygen, workouts and every other metric Health Auto Export can send, as cards with trends over 7/30/90/365 days. Per profile and private by construction — each profile mints its own **write-only** ingest key, the phone's data lands in its own file, and re-sends are de-duplicated, so an automation firing every five minutes never counts a day twice. See [docs/HEALTH.md](docs/HEALTH.md)
- 📦 **Yours to keep** — one-tap JSON export/import, guest mode, **no telemetry**; switching kg ↔ lb offers to convert every stored number
- 🤖 **Ask an AI about your training** (optional) — an [MCP server](mcp/README.md) lets a client like Claude Desktop or Cursor read your history in your own words: *"what did I bench last week?"*. Read-only, spawned locally by the client, nothing leaves your box. Not in the Docker build — if you don't use an AI assistant, it isn't there
+24
View File
@@ -78,6 +78,30 @@ sitting inside somebody's house:
- Both routes need a session — not to protect public podcasts, but because this process fetches on
behalf of whoever asks.
## The full player
Tap the bar — the cover and the text, not the buttons — and it opens the full player, the way tapping
Spotify's bar does: artwork at size, the whole episode title, the show, the author, the episode number
and date, a **scrubber you can drag**, elapsed and **remaining**, −15 / +30, previous and next, and a
line that names **what plays next** ("Then: …") or says that this is the last one in the list.
It opens as a **sheet**, not a route, for the same reason the bar lives above the router: a screen
inside the router is unmounted by navigating, and this must never be the thing that stops the audio.
Swipe down (or Android back) closes it and playback continues.
A station gets the same sheet without the scrubber: a live stream has no position and no end, and
saying so is better than a slider that does nothing.
## When an episode ends
The next one in the list you tapped from plays, with nobody touching the phone. "Next" is literally
the next row of that list — the order you can see — and at the end of it playback stops, which the
full player says *before* it happens. The finished episode is marked heard first, so what you have
listened to stays that way.
The lock screen's next/previous buttons do the same thing, which is the point: that is where somebody
with their hands on a bar is going to press it.
## The player, and the two things that are easy to get wrong
- **Audio only starts inside the tap.** iOS allows audio to begin from a user gesture and from
+4
View File
@@ -83,6 +83,10 @@ rest timer, on purpose — a second floating bar with its own look reads as a se
- **pause** — keeps the station, so the same one is still there after the rest
- **stop** — takes the bar and the station away
Tapping the bar itself opens the full player — the logo at size, the station, its genre, what it
says it is playing, and pause/stop — with **no scrubber and no clock**, because a live stream has no
position and no end, and a slider that does nothing is worse than a sentence that says so.
**Media Session** is what puts the station, the track and the controls on the lock screen and in the
car, and it is what makes "screen off, phone in pocket" work: the audio is played by the browser
underneath the page, not by the page's timers. Those timers — the 45-second poll for what is playing —
+137
View File
@@ -0,0 +1,137 @@
/* The full player: what the bar opens when you tap it, the way tapping Spotify's bar does.
*
* The bar is a glance — one line, under a thumb, over whatever screen you were on. This is the other
* half: the artwork at size, the whole episode title instead of the truncated one, a bar you can
* actually drag, and the number that decides whether to start something else (how much is *left*).
*
* It is a **sheet**, not a route, and that is the same decision as the bar living above the router: a
* screen inside the router is unmounted by navigating, and this must never be the thing that stops
* the audio. A sheet brings the house behaviour with it — swipe down to dismiss, Android's back
* closes it, the page behind it does not scroll — and `data-nodrag` on the scrubber (the Slider
* component already carries it) is what keeps a sideways drag from being read as a dismissal.
*
* Nothing here owns the audio: every control goes to the store, which goes to the one element in
* lib/player.js.
*/
import { useEffect, useState } from 'react'
import { useUI } from '../store/useUI.js'
import { t } from '../lib/i18n.js'
import { fmtClock, nextEpisode, prevEpisode, progressPct } from '../lib/podcast-view.js'
import { Slider, Button } from './ui.jsx'
import Icon from './Icon.jsx'
export default function NowPlaying({ close }) {
const radio = useUI(s => s.radio)
const pod = useUI(s => s.pod)
const { togglePod, stopPod, podSeek, podSeekTo, podNext, podPrev, toggleRadio, stopRadio } = useUI()
/* Stopped from somewhere else — the bar's ✕, or the end of the queue with nothing after it — and
this closes itself rather than staying open on an empty screen. */
useEffect(() => { if (!radio && !pod) close() }, [radio, pod])
if (!radio && !pod) return null
if (pod) {
const { episode, show } = pod
const duration = Number(pod.duration) || Number(episode.duration) || 0
const next = nextEpisode(pod.queue, episode.id)
const prev = prevEpisode(pod.queue, episode.id)
return <div className="np">
<Head onClose={close} />
<Art image={episode.image || show?.image || null} />
<div className="np-meta">
<div className="np-show">{show?.name || t('Podcast')}</div>
<div className="np-title">{episode.title}</div>
<div className="np-sub">
{[show?.author, episode.episode ? t('Episode {0}', episode.episode) : null, episode.date?.slice(0, 10)]
.filter(Boolean).join(' · ')}
</div>
</div>
<div className="np-scrub">
<Slider value={Math.min(pod.position || 0, duration || 1)} min={0} max={duration || 1} step={1}
onChange={v => podSeekTo(v)} />
<div className="np-times">
<span>{fmtClock(pod.position)}</span>
{/* What is left, not the total: the total is on the bar and on the right of the scrubber
a moment ago, and the question here is whether there is time for another one. */}
<span>{duration ? '-' + fmtClock(Math.max(0, duration - (pod.position || 0))) : ''}</span>
</div>
</div>
<div className="np-controls">
<button className="np-skip" onClick={() => podSeek(-15)} disabled={!duration} aria-label={t('15 seconds back')}>−15</button>
<button className="np-main" onClick={togglePod} aria-label={pod.playing ? t('Pause') : t('Play')}>
<Icon name={pod.playing ? 'pause' : 'play'} />
</button>
<button className="np-skip" onClick={() => podSeek(30)} disabled={!duration} aria-label={t('30 seconds forward')}>+30</button>
</div>
<div className="np-foot">
<button className="np-nav" onClick={podPrev} disabled={!prev} aria-label={t('Previous episode')}>
<Icon name="chevronLeft" />{t('Previous')}
</button>
<span className="np-pct">{(() => {
const pct = progressPct({ pos: pod.position, dur: duration }, duration)
return pct == null ? '' : Math.round(pct) + '%'
})()}</span>
<button className="np-nav" onClick={podNext} disabled={!next} aria-label={t('Next episode')}>
{t('Next')}<Icon name="chevronRight" />
</button>
</div>
{/* What plays when this one ends — or that nothing will. The queue is the list the episode was
tapped in, in the order it was shown, so "next" is the row below the one you pressed. */}
<div className="np-nextline">
{next ? t('Then: {0}', next.title) : t('Last episode in this list.')}
</div>
<div className="np-actions">
<Button variant="plain" size="sm" onClick={stopPod}>{t('Stop')}</Button>
</div>
</div>
}
const station = radio.station
const cover = radio.now?.cover || station.image || null
return <div className="np">
<Head onClose={close} />
<Art image={cover} />
<div className="np-meta">
<div className="np-show">{t('Radio')}</div>
<div className="np-title">{station.name}</div>
<div className="np-sub">{[station.detail, station.genre].filter(Boolean).join(' · ')}</div>
</div>
<div className="np-meta">
<div className="np-sub">
{radio.now
? t('Playing now: {0}', [radio.now.artist, radio.now.title].filter(Boolean).join(' · '))
: t('This station does not publish what it is playing.')}
</div>
</div>
<div className="np-controls">
<button className="np-main" onClick={toggleRadio} aria-label={radio.playing ? t('Pause') : t('Play')}>
<Icon name={radio.playing ? 'pause' : 'play'} />
</button>
</div>
{/* No scrubber, no clock, and saying so is better than a slider that does nothing: a live stream
has no position, no end, and nothing to go back to. */}
<div className="np-nextline">{t('Live radio: there is nothing to seek and nothing to skip.')}</div>
<div className="np-actions">
<Button variant="plain" size="sm" onClick={stopRadio}>{t('Stop')}</Button>
</div>
</div>
}
const Head = ({ onClose }) => <div className="np-head">
<button className="iconbtn" onClick={onClose} aria-label={t('Close')}><Icon name="chevronDown" /></button>
<span className="np-head-t">{t('Now playing')}</span>
<span style={{ width: 34 }} />
</div>
/** The artwork at size — and the placeholder when there is none, which is a third of podcasts. */
const Art = ({ image }) => {
const [bad, setBad] = useState(null)
return image && image !== bad
? <img className="np-art" src={image} alt="" onError={() => setBad(image)} />
: <div className="np-art np-art-ph"><Icon name="music" /></div>
}
+191
View File
@@ -0,0 +1,191 @@
// @vitest-environment happy-dom
/* The full player: the sheet the bar opens.
*
* Worth a test because it is mostly *claims* — "this is what is playing", "this is how much is
* left", "this is what plays next" — and a claim that drifts from the store is worse than no player
* at all. Two of them are load-bearing here:
*
* - **What plays next is named**, so continuing is not a surprise and stopping is not either.
* - **A station gets no scrubber.** A live stream has no position and no end; a slider that does
* nothing is worse than saying so.
*
* The `<audio>` element lives in lib/player.js, outside React, and is mocked: this file is about what
* the sheet draws and which store action each control calls. */
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 seekBy = vi.fn(() => 100)
const seekTo = vi.fn(() => 900)
vi.mock('../lib/player.js', () => ({
playStream: vi.fn(() => true),
playFile: vi.fn(() => true),
pausePlayer: vi.fn(),
resumePlayer: vi.fn(() => true),
seekBy: (...a) => seekBy(...a),
seekTo: (...a) => seekTo(...a),
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: NowPlaying } = await import('./NowPlaying.jsx')
const show = { feed: 'https://a.example.com/feed', name: 'Tiene Sentido', author: 'Eli Romero', image: null }
const ep = (over = {}) => ({
id: 'ep-1', title: 'Experta en Inflamación: cómo sanar tu intestino',
url: 'https://audio.example.com/1.mp3', date: '2025-09-21T10:00:00.000Z', duration: 3600, image: null, ...over
})
const station = { src: 'soma', id: 'beatblender', name: 'Beat Blender', detail: 'A late night blend', genre: 'Electronic', url: 'https://ice2.somafm.com/x-128-mp3', image: null }
let host, root, closed
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
seekBy.mockClear(); seekTo.mockClear()
closed = vi.fn()
host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
act(() => { useUI.setState({ pod: null, radio: null }) })
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const mount = async (close = closed) => { await act(async () => { root.render(<NowPlaying close={close} />) }) }
const btn = label => [...host.querySelectorAll('button')].find(b => b.getAttribute('aria-label') === label)
const text = () => host.textContent
describe('an episode in the full player', () => {
const open = async (over = {}, podOver = {}) => {
act(() => { useUI.getState().playEpisode(show, ep(over), podOver.queue || []) })
await mount()
if (podOver.position != null) act(() => { useUI.getState().setPodPlayback({ position: podOver.position, duration: podOver.duration || 3600 }) })
await act(async () => {})
}
it('shows the episode, the show, the author and the whole title', async () => {
await open()
expect(host.querySelector('.np-show').textContent).toBe('Tiene Sentido')
expect(host.querySelector('.np-title').textContent).toContain('Experta en Inflamación')
expect(text()).toContain('Eli Romero')
expect(text()).toContain('2025-09-21')
})
it('counts down what is left, which is the number that decides whether to start something else', async () => {
await open({ duration: 3600 }, { position: 900, duration: 3600 })
const [elapsed, left] = [...host.querySelectorAll('.np-times span')].map(s => s.textContent)
expect(elapsed).toBe('15:00')
expect(left).toBe('-45:00')
})
it('drags the scrubber to a position', async () => {
await open({ duration: 3600 }, { position: 900, duration: 3600 })
const sld = host.querySelector('.np-scrub .sld')
// The Slider is pointer-driven, so a press on the track is a seek to that fraction of the file.
sld.getBoundingClientRect = () => ({ left: 0, width: 200, top: 0, height: 20, right: 200, bottom: 20 })
act(() => {
const down = new window.PointerEvent('pointerdown', { bubbles: true, clientX: 100, pointerId: 1 })
sld.dispatchEvent(down)
})
await act(async () => {})
expect(seekTo).toHaveBeenCalled()
expect(seekTo.mock.calls[0][0]).toBeGreaterThan(1700)
expect(seekTo.mock.calls[0][0]).toBeLessThan(1900)
})
it('skips back and forward through the element', async () => {
await open()
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])
})
it('names what plays next, so continuing is not a surprise', async () => {
const first = ep(), second = ep({ id: 'ep-2', title: 'La crisis de la salud mental' })
await open(first, { queue: [first, second] })
expect(host.querySelector('.np-nextline').textContent).toBe('Then: La crisis de la salud mental')
expect(btn('Next episode').disabled).toBe(false)
})
it('says when there is nothing after this one, and disables the button', async () => {
const only = ep()
await open(only, { queue: [only] })
expect(host.querySelector('.np-nextline').textContent).toBe('Last episode in this list.')
expect(btn('Next episode').disabled).toBe(true)
expect(btn('Previous episode').disabled).toBe(true)
})
it('goes to the next episode, and back', async () => {
const first = ep(), second = ep({ id: 'ep-2', title: 'Dos' })
await open(first, { queue: [first, second] })
act(() => { btn('Next episode').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useUI.getState().pod.episode.id).toBe('ep-2')
act(() => { btn('Previous episode').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useUI.getState().pod.episode.id).toBe('ep-1')
})
it('pauses, and stops', async () => {
await open()
act(() => { btn('Pause').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(useUI.getState().pod.playing).toBe(false)
act(() => { [...host.querySelectorAll('button')].find(b => b.textContent.trim() === 'Stop').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useUI.getState().pod).toBe(null)
// Stopping from the sheet closes it, instead of leaving an empty player on screen.
expect(closed).toHaveBeenCalled()
})
it('falls back to the placeholder when the artwork does not load', async () => {
await open({ image: 'https://x/not-an-image' })
expect(host.querySelector('.np-art').tagName).toBe('IMG')
act(() => { host.querySelector('.np-art').dispatchEvent(new Event('error')) })
await act(async () => {})
expect(host.querySelector('.np-art').className).toContain('np-art-ph')
})
})
describe('a station in the full player', () => {
const open = async (now = null) => {
act(() => {
useUI.getState().playRadio(station)
if (now) useUI.getState().setRadioNow(now)
})
await mount()
}
it('shows the station and what it says it is playing', async () => {
await open({ artist: 'Tycho', title: 'From Home' })
expect(host.querySelector('.np-title').textContent).toBe('Beat Blender')
expect(text()).toContain('A late night blend · Electronic')
expect(text()).toContain('Playing now: Tycho · From Home')
})
it('says so when the station publishes no track', async () => {
await open()
expect(text()).toContain('does not publish what it is playing')
})
it('offers no scrubber, because a live stream has nothing to seek', async () => {
await open({ artist: 'Tycho', title: 'From Home' })
expect(host.querySelector('.np-scrub')).toBe(null)
expect(text()).toContain('nothing to seek')
// And no next/previous: a station has no queue, and playing the next one is not a thing.
expect(btn('Next episode')).toBeUndefined()
})
it('pauses the station from here', async () => {
await open()
act(() => { btn('Pause').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(useUI.getState().radio.playing).toBe(false)
expect(useUI.getState().radio.station.id).toBe('beatblender')
})
})
+27 -13
View File
@@ -25,6 +25,7 @@ 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'
import NowPlaying from './NowPlaying.jsx'
/* How often the station is asked what it is playing.
*
@@ -40,23 +41,29 @@ const NOW_EVERY_MS = 45000
export default function PlayerBar() {
const radio = useUI(s => s.radio)
const pod = useUI(s => s.pod)
const openSheet = useUI(s => s.openSheet)
const { toggleRadio, stopRadio, setRadioNow, togglePod, stopPod, podSeek, podNext } = useUI()
const on = !!radio || !!pod
/* Tapping the bar opens the full player, the way tapping Spotify's bar does. A sheet and not a
route: a route would be unmounted by navigating, and this is one tap away from every screen in
the app. The sheet's own gestures (swipe down, Android back) come with it. */
const openFull = () => openSheet(close => <NowPlaying close={close} />)
// 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} />
if (radio) return <RadioLine radio={radio} onToggle={toggleRadio} onStop={stopRadio} onNow={setRadioNow} onOpen={openFull} />
if (pod) return <EpisodeLine pod={pod} onToggle={togglePod} onStop={stopPod} onSeek={podSeek} onNext={podNext} onOpen={openFull} />
return null
}
/* ---------- radio ---------- */
function RadioLine({ radio, onToggle, onStop, onNow }) {
function RadioLine({ radio, onToggle, onStop, onNow, onOpen }) {
const station = radio.station
// Poll for what is playing, only for the sources that publish it (the api answers null for the
@@ -77,6 +84,7 @@ function RadioLine({ radio, onToggle, onStop, onNow }) {
: (station.detail || station.genre || t('Live radio'))
return <Bar
onOpen={onOpen}
cover={radio.now?.cover || station.image || null}
name={station.name}
line={line}
@@ -91,7 +99,7 @@ function RadioLine({ radio, onToggle, onStop, onNow }) {
/* ---------- an episode ---------- */
function EpisodeLine({ pod, onToggle, onStop, onSeek, onNext }) {
function EpisodeLine({ pod, onToggle, onStop, onSeek, onNext, onOpen }) {
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
@@ -99,6 +107,7 @@ function EpisodeLine({ pod, onToggle, onStop, onSeek, onNext }) {
: fmtClock(pod.position)
return <Bar
onOpen={onOpen}
cover={pod.episode.image || pod.show?.image || null}
name={pod.show?.name || t('Podcast')}
line={pod.episode.title}
@@ -119,20 +128,25 @@ function EpisodeLine({ pod, onToggle, onStop, onSeek, onNext }) {
</>} />
}
/** 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 }) {
/** The line itself, shared by both: cover, two lines of text, the controls, a progress hairline.
*
* The cover and the text are the button that opens the full player — the controls are buttons of
* their own, and a bar where the whole surface is one button cannot have a play button in it. */
function Bar({ onOpen, 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="plr-open" onClick={onOpen} aria-label={t('Open the 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>
<button className="iconbtn plr-btn plr-toggle" onClick={onToggle} aria-label={label}>
<Icon name={icon} />
</button>
+29 -2
View File
@@ -19,6 +19,7 @@ vi.mock('../lib/api.js', () => ({ api: (...a) => api(...a) }))
const playStream = vi.fn(() => true)
const playFile = vi.fn(() => true)
const seekBy = vi.fn(() => 100)
const setStreamSession = vi.fn()
vi.mock('../lib/player.js', () => ({
playStream: (...a) => playStream(...a),
playFile: (...a) => playFile(...a),
@@ -28,7 +29,7 @@ vi.mock('../lib/player.js', () => ({
seekTo: vi.fn(() => 0),
playerTime: () => ({ position: 0, duration: null }),
setPlayerVolume: vi.fn(),
setStreamSession: vi.fn(),
setStreamSession: (...a) => setStreamSession(...a),
setEpisodeSession: vi.fn(),
setSessionPosition: vi.fn(),
wireSessionHandlers: vi.fn(),
@@ -37,6 +38,7 @@ vi.mock('../lib/player.js', () => ({
}))
const { default: PlayerBar } = await import('./PlayerBar.jsx')
const { default: Modals } = await import('./Modals.jsx')
const station = (over = {}) => ({
src: 'soma', id: 'beatblender', name: 'Beat Blender',
@@ -57,13 +59,17 @@ beforeEach(() => {
playStream.mockClear()
playFile.mockClear()
seekBy.mockClear()
setStreamSession.mockClear()
host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
act(() => { useUI.setState({ radio: null, pod: null }) })
act(() => { useUI.setState({ radio: null, pod: null, sheets: [] }) })
document.getElementById('modal-root')?.remove()
})
afterEach(() => {
act(() => root.unmount())
host.remove()
document.body.classList.remove('playing-media')
act(() => { useUI.setState({ sheets: [] }) })
document.getElementById('modal-root')?.remove()
})
const mount = async () => { await act(async () => { root.render(<PlayerBar />) }) }
@@ -87,6 +93,9 @@ describe('the player bar', () => {
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')
// The lock screen gets the track too, not just the station: the metadata has to be re-sent when
// the track changes, and this is the only place that knows it changed.
expect(setStreamSession).toHaveBeenLastCalledWith(expect.objectContaining({ id: 'beatblender' }), expect.objectContaining({ title: 'Little Fluffy Clouds' }))
})
it('pauses a station without losing it', async () => {
@@ -170,6 +179,24 @@ describe('the player bar', () => {
expect(playFile).toHaveBeenCalledWith(episode().url, { startAt: 620 })
})
/* The bar is a glance and the full player is the detail, and the tap between them is the whole
interaction: tapping the bar must not pause, stop, or navigate anything. */
it('opens the full player when the bar itself is tapped', async () => {
act(() => { useUI.getState().playEpisode(show, episode({ duration: 3600 }), []) })
await act(async () => { root.render(<><PlayerBar /><Modals /></>) })
expect(document.querySelector('#modal-root .np')).toBe(null)
act(() => { host.querySelector('.plr-open').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
const sheet = document.querySelector('#modal-root .np')
expect(sheet).toBeTruthy()
expect(sheet.textContent).toContain('Nadie Sabe Nada')
expect(sheet.textContent).toContain('En el corazón del ajo')
// Still playing: opening the detail view is not a play/pause.
expect(useUI.getState().pod.playing).toBe(true)
expect(playFile).toHaveBeenCalledTimes(1)
})
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()
+44
View File
@@ -1156,6 +1156,47 @@ body.chips-dragging *{cursor:inherit}
.pod-ep-s{font-size:11.5px;color:var(--label-3)}
.pod-heard{color:var(--acc)}
/* The full player, inside a sheet: artwork at size, the whole title, a draggable bar.
It is the other half of the strip under the tab bar — that one is a glance, this one is where
somebody looks when the question is "what is this, and how much is left". */
.np{display:flex;flex-direction:column;gap:14px;padding-bottom:4px}
.np-head{display:flex;align-items:center;justify-content:space-between;gap:8px}
.np-head-t{font-size:12px;font-weight:600;letter-spacing:.06em;text-transform:uppercase;color:var(--label-3)}
.np-art{
width:min(62vw,240px);height:min(62vw,240px);border-radius:var(--r-lg);object-fit:cover;
align-self:center;box-shadow:0 18px 40px -14px rgba(0,0,0,.5);
}
.np-art-ph{display:flex;align-items:center;justify-content:center;background:var(--surface-3);color:var(--label-3);box-shadow:none}
.np-art-ph .icn{font-size:52px}
.np-meta{display:flex;flex-direction:column;gap:3px;text-align:center;padding:0 4px}
.np-show{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--label-3)}
.np-title{font-size:17px;font-weight:650;color:var(--label);line-height:1.32}
.np-sub{font-size:12.5px;color:var(--label-3);line-height:1.4}
.np-scrub{display:flex;flex-direction:column;gap:6px;padding:0 2px}
.np-times{display:flex;justify-content:space-between;font-size:11.5px;color:var(--label-3);font-variant-numeric:tabular-nums}
.np-controls{display:flex;align-items:center;justify-content:center;gap:22px}
/* The one big button on the screen, and the two that are only ever pressed by feel. */
.np-main{
width:64px;height:64px;border-radius:50%;border:0;background:var(--acc);color:var(--on-acc);
display:flex;align-items:center;justify-content:center;cursor:pointer;
}
.np-main .icn{font-size:28px;--icon-stroke:2.4}
.np-skip{
min-width:52px;height:44px;border-radius:12px;border:0;background:var(--surface-3);color:var(--label);
font:650 14px/1 var(--font);font-variant-numeric:tabular-nums;cursor:pointer;
}
.np-skip:disabled{color:var(--label-4);background:transparent}
.np-foot{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:0 2px}
.np-nav{
display:flex;align-items:center;gap:4px;border:0;background:transparent;color:var(--label);
font:600 13px/1 var(--font);padding:8px 6px;border-radius:10px;cursor:pointer;
}
.np-nav:disabled{color:var(--label-4)}
.np-nav .icn{font-size:17px}
.np-pct{font-size:11.5px;color:var(--label-3);font-variant-numeric:tabular-nums}
.np-nextline{font-size:12px;color:var(--label-3);text-align:center;line-height:1.45;padding:0 8px}
.np-actions{display:flex;justify-content:center}
/* 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.
@@ -1183,6 +1224,9 @@ body.playing-media #app{padding-bottom:calc(146px + 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}
/* The cover and the text are one button: tapping them opens the full player, and the controls
beside them stay buttons of their own. */
.plr-open{display:flex;align-items:center;gap:10px;flex:1;min-width:0;border:0;background:transparent;padding:0;text-align:left;cursor:pointer}
.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}
+17 -2
View File
@@ -220,9 +220,18 @@ export function setSessionPosition(duration = durationOf(), position = positionO
}
/* 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. */
rather than per track: `play` and `pause` mean the same thing for a station and an episode.
*
* `next` and `previous` are passed in because only the store knows what a queue is — but they are
* kept in module state and read *late*, so the handler can be installed once and still follow the
* queue the current episode was started from. That is what puts "next episode" on the lock screen,
* which is where somebody with their hands on a bar is going to press it. */
let sessionWired = false
export function wireSessionHandlers() {
let sessionNext = null
let sessionPrev = null
export function wireSessionHandlers({ next = null, prev = null } = {}) {
if (next) sessionNext = next
if (prev) sessionPrev = prev
const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
if (!ms || sessionWired) return
sessionWired = true
@@ -233,6 +242,8 @@ export function wireSessionHandlers() {
ms.setActionHandler?.('seekbackward', () => seekBy(-15))
ms.setActionHandler?.('seekforward', () => seekBy(30))
ms.setActionHandler?.('seekto', e => { if (e?.seekTime != null) seekTo(e.seekTime) })
ms.setActionHandler?.('nexttrack', () => { sessionNext?.() })
ms.setActionHandler?.('previoustrack', () => { sessionPrev?.() })
} catch { /* a browser without those actions */ }
}
@@ -248,6 +259,8 @@ export function clearSession() {
ms.setActionHandler?.('seekbackward', null)
ms.setActionHandler?.('seekforward', null)
ms.setActionHandler?.('seekto', null)
ms.setActionHandler?.('nexttrack', null)
ms.setActionHandler?.('previoustrack', null)
} catch { /* as above */ }
}
@@ -258,4 +271,6 @@ export function __resetPlayer() {
handlers = new Set()
pendingStart = 0
sessionWired = false
sessionNext = null
sessionPrev = null
}
+9
View File
@@ -186,6 +186,14 @@ describe('the lock screen', () => {
const el = playerEl()
wireSessionHandlers()
wireSessionHandlers()
// Next and previous go through whichever queue the current episode came from, read late: the
// handlers are installed once, and the store swaps the callbacks as the queue changes.
const next = vi.fn(), prev = vi.fn()
wireSessionHandlers({ next, prev })
session.handlers.nexttrack()
session.handlers.previoustrack()
expect(next).toHaveBeenCalled()
expect(prev).toHaveBeenCalled()
expect(typeof session.handlers.pause).toBe('function')
expect(typeof session.handlers.seekbackward).toBe('function')
playFile('https://audio.example.com/1.mp3')
@@ -209,5 +217,6 @@ describe('the lock screen', () => {
expect(session.metadata).toBe(null)
expect(session.handlers.play).toBe(null)
expect(session.handlers.pause).toBe(null)
expect(session.handlers.nexttrack).toBe(null)
})
})
+10
View File
@@ -1408,6 +1408,16 @@ 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}',
'Now playing': 'Sonando ahora',
'Open the player': 'Abrir el reproductor',
'Previous': 'Anterior',
'Previous episode': 'Episodio anterior',
'Episode {0}': 'Episodio {0}',
'Then: {0}': 'Después: {0}',
'Last episode in this list.': 'Es el último episodio de esta lista.',
'Playing now: {0}': 'Suena ahora: {0}',
'This station does not publish what it is playing.': 'Esta emisora no publica qué está sonando.',
'Live radio: there is nothing to seek and nothing to skip.': 'Radio en vivo: no hay nada que adelantar ni saltar.',
// podcasts
'Live radio, nothing downloaded': 'Radio en vivo, sin descargar nada',
'Spanish podcasts, remembered where you left off': 'Podcasts en español, que se acuerdan de dónde ibas',
+13 -20
View File
@@ -3,7 +3,7 @@ import { uid } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { api } from '../lib/api.js'
import {
playStream, playFile, pausePlayer, resumePlayer, seekBy, setPlayerVolume,
playStream, playFile, pausePlayer, resumePlayer, seekBy, seekTo, setPlayerVolume,
setStreamSession, setEpisodeSession, setSessionPosition, wireSessionHandlers,
clearSession, playerTime, onPlayer
} from '../lib/player.js'
@@ -211,7 +211,8 @@ export const useUI = create((set, get) => ({
}
})
setEpisodeSession(show, episode)
wireSessionHandlers()
// The lock screen's next/previous go through the queue this episode came from.
wireSessionHandlers({ next: () => get().podNext(), prev: () => get().podPrev() })
savePodPosition(true)
return ok
},
@@ -243,6 +244,16 @@ export const useUI = create((set, get) => ({
set({ pod: { ...p, position: to } })
setSessionPosition()
},
/** Somewhere in particular: the scrubber in the full player, and the lock screen's own bar. */
podSeekTo(seconds) {
const p = get().pod
if (!p) return
const to = seekTo(seconds)
if (to == null) return
set({ pod: { ...p, position: to } })
setSessionPosition()
savePodPosition(true)
},
podNext() {
const p = get().pod
if (!p) return false
@@ -291,24 +302,6 @@ export const useUI = create((set, get) => ({
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
nothing. It works on Android and desktop, where the element's volume is real. */
setRadioVolume(volume) {
const r = get().radio
setStreamVolume(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 } })
setMediaSession(r.station, now)
},
startRest(sec, forIdx) {
get().stopRest()
// Rest timer set to Off. Stopping and returning rather than starting a zero-length timer
+215
View File
@@ -0,0 +1,215 @@
// @vitest-environment happy-dom
/* The podcast player's state machine: what happens when an episode ends, and where it starts.
*
* Two behaviours the user asked for in as many words, and both are the kind that only show up an
* hour into a workout — which is exactly when nobody wants to discover them:
*
* - **When an episode ends, the next one plays.** "Next" is the next row of the list the episode
* was tapped in, because that is what the person can see; at the end of that list it stops, and
* the full player says so before it happens.
* - **An episode starts where it was left off**, and if it was left within seconds of the end it
* starts over instead.
*
* The player module is mocked with a captured handler list, so the test can *emit* what a browser
* emits — `ended`, `time`, `paused` — instead of pretending the audio exists. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
/* `vi.hoisted` because the module under test registers its listener at *import* time: anything the
factory closes over has to exist before the imports are evaluated, which is what this is for. */
const mocks = vi.hoisted(() => ({
handlers: [],
/* What the element would answer if it were asked where it is. The store asks the *element*, not the
event that just arrived, so a test that wants a position saved has to move this too — which is
the honest shape of it: the audio is the truth and the store follows. */
time: { position: 0, duration: null },
playStream: vi.fn(() => true),
playFile: vi.fn(() => true),
pausePlayer: vi.fn(),
seekBy: vi.fn(() => 0)
}))
vi.mock('../lib/player.js', () => ({
playStream: (...a) => mocks.playStream(...a),
playFile: (...a) => mocks.playFile(...a),
pausePlayer: (...a) => mocks.pausePlayer(...a),
resumePlayer: vi.fn(() => true),
seekBy: (...a) => mocks.seekBy(...a),
seekTo: vi.fn(() => 0),
playerTime: () => mocks.time,
setPlayerVolume: vi.fn(),
setStreamSession: vi.fn(),
setEpisodeSession: vi.fn(),
setSessionPosition: vi.fn(),
wireSessionHandlers: vi.fn(),
clearSession: vi.fn(),
onPlayer: h => { mocks.handlers.push(h); return () => {} }
}))
import { useUI } from './useUI.js'
import { useStore } from './useStore.js'
const emit = (event, state = { position: 0, duration: null }) => mocks.handlers.forEach(h => h(event, state))
const ep = (over = {}) => ({
id: 'ep-1', title: 'Uno', 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: 'Tiene Sentido' }
beforeEach(() => {
vi.useFakeTimers()
mocks.playFile.mockClear(); mocks.pausePlayer.mockClear(); mocks.seekBy.mockClear()
mocks.time = { position: 0, duration: null }
useUI.setState({ pod: null, radio: null })
useStore.setState(s => ({ S: { ...s.S, podcasts: { shows: [], progress: {} } } }))
})
afterEach(() => { vi.useRealTimers() })
describe('playing an episode', () => {
it('starts it where it was left off, on this device or another', () => {
useStore.getState().savePodcastPosition('ep-1', 600, 3135)
useUI.getState().playEpisode(show, ep(), [ep()])
expect(mocks.playFile).toHaveBeenCalledWith('https://audio.example.com/1.mp3', { startAt: 600 })
expect(useUI.getState().pod.position).toBe(600)
})
it('starts a finished episode over instead of resuming into its last seconds', () => {
useStore.getState().savePodcastPosition('ep-1', 3130, 3135)
useUI.getState().playEpisode(show, ep(), [ep()])
expect(mocks.playFile).toHaveBeenCalledWith(expect.any(String), { startAt: 0 })
})
it('keeps the list it was tapped in as the queue, and a lone episode as a queue of one', () => {
const one = ep(), two = ep({ id: 'ep-2', title: 'Dos' })
useUI.getState().playEpisode(show, one, [one, two])
expect(useUI.getState().pod.queue.map(e => e.id)).toEqual(['ep-1', 'ep-2'])
useUI.getState().playEpisode(show, ep({ id: 'ep-9' }), [])
expect(useUI.getState().pod.queue.map(e => e.id)).toEqual(['ep-9'])
})
})
describe('when an episode ends', () => {
it('plays the next one in the list, without anybody touching the phone', () => {
const one = ep(), two = ep({ id: 'ep-2', title: 'Dos', url: 'https://audio.example.com/2.mp3' })
useUI.getState().playEpisode(show, one, [one, two])
mocks.playFile.mockClear()
mocks.time = { position: 3135, duration: 3135 }
emit('ended', { position: 3135, duration: 3135 })
expect(mocks.playFile).toHaveBeenCalledWith('https://audio.example.com/2.mp3', { startAt: 0 })
expect(useUI.getState().pod.episode.id).toBe('ep-2')
expect(useUI.getState().pod.show.name).toBe('Tiene Sentido')
})
it('marks the finished one as heard before moving on', () => {
const one = ep(), two = ep({ id: 'ep-2' })
useUI.getState().playEpisode(show, one, [one, two])
mocks.time = { position: 3135, duration: 3135 }
emit('ended', { position: 3135, duration: 3135 })
expect(useStore.getState().S.podcasts.progress['ep-1'].pos).toBe(3135)
// And the next one is not "heard" just because it started.
expect(useStore.getState().S.podcasts.progress['ep-2']).toBeUndefined()
})
it('stops at the end of the list, because there is nothing after it', () => {
const one = ep(), two = ep({ id: 'ep-2' })
useUI.getState().playEpisode(show, two, [one, two])
mocks.pausePlayer.mockClear()
emit('ended', { position: 3135, duration: 3135 })
expect(mocks.pausePlayer).toHaveBeenCalled()
expect(useUI.getState().pod.playing).toBe(false)
// The episode stays on screen: it is still what you were listening to, and the sheet says
// "last episode in this list" rather than leaving a blank player.
expect(useUI.getState().pod.episode.id).toBe('ep-2')
})
it('stops a lone episode that ended, and does not invent a next one', () => {
const only = ep()
useUI.getState().playEpisode(show, only, [only])
mocks.playFile.mockClear()
emit('ended', { position: 100, duration: 3135 })
expect(mocks.playFile).not.toHaveBeenCalled()
expect(useUI.getState().pod.playing).toBe(false)
})
})
describe('what the player reports back', () => {
it('moves the clock on screen once per second, not four times', () => {
useUI.getState().playEpisode(show, ep(), [])
const before = useUI.getState().pod
emit('time', { position: 10.2, duration: 3135 })
expect(useUI.getState().pod.position).toBe(10.2)
// Same second: the store object is not replaced, so nothing re-renders for it.
const same = useUI.getState().pod
emit('time', { position: 10.7, duration: 3135 })
expect(useUI.getState().pod).toBe(same)
emit('time', { position: 11.1, duration: 3135 })
expect(useUI.getState().pod).not.toBe(before)
})
it('writes the position into the profile when the episode is paused', () => {
vi.setSystemTime(1000)
useUI.getState().playEpisode(show, ep(), [])
vi.setSystemTime(1000 + 8000)
mocks.time = { position: 620, duration: 3135 }
emit('paused', { position: 620, duration: 3135 })
expect(useStore.getState().S.podcasts.progress['ep-1']).toMatchObject({ pos: 620, dur: 3135 })
expect(useUI.getState().pod.playing).toBe(false)
})
it('does not write down a two-second listen', () => {
vi.setSystemTime(1000)
useUI.getState().playEpisode(show, ep(), [])
vi.setSystemTime(2000)
mocks.time = { position: 2, duration: 3135 }
emit('paused', { position: 2, duration: 3135 })
expect(useStore.getState().S.podcasts.progress['ep-1']).toBeUndefined()
})
it('takes the length from the loaded file, so the bar has a clock', () => {
useUI.getState().playEpisode(show, ep({ duration: null }), [])
emit('meta', { position: 0, duration: 2480 })
expect(useUI.getState().pod.duration).toBe(2480)
})
it('says it stopped when the file dies, instead of claiming to play', () => {
useUI.getState().playEpisode(show, ep(), [])
emit('error', { position: 12, duration: 3135 })
expect(useUI.getState().pod.playing).toBe(false)
})
})
describe('the controls the full player uses', () => {
it('seeks to a position when the scrubber is dragged', () => {
useUI.getState().playEpisode(show, ep(), [])
useUI.getState().podSeekTo(900)
expect(useUI.getState().pod.position).toBe(0) // the mocked element answers 0
// The real call went to the element; the store keeps whatever it says it landed on.
expect(mocks.seekBy).not.toHaveBeenCalled()
})
it('skips by seconds through the element, and follows what it answers', () => {
useUI.getState().playEpisode(show, ep(), [])
useUI.getState().podSeek(-15)
expect(mocks.seekBy).toHaveBeenCalledWith(-15)
useUI.getState().podSeek(30)
expect(mocks.seekBy).toHaveBeenLastCalledWith(30)
})
it('stops everything and forgets the station when the podcast is stopped', () => {
useUI.getState().playEpisode(show, ep(), [])
useUI.getState().stopPod()
expect(useUI.getState().pod).toBe(null)
expect(mocks.pausePlayer).toHaveBeenCalled()
})
it('never lets a station and an episode play at once', () => {
useUI.getState().playEpisode(show, ep(), [])
useUI.getState().playRadio({ src: 'soma', id: 'x', name: 'X', url: 'https://ice2.somafm.com/x-128-mp3' })
expect(useUI.getState().pod).toBe(null)
expect(useUI.getState().radio.station.id).toBe('x')
useUI.getState().playEpisode(show, ep(), [])
expect(useUI.getState().radio).toBe(null)
expect(useUI.getState().pod.episode.id).toBe('ep-1')
})
})