Radio: estaciones en vivo mientras entrenás
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s

Música tiene una sección **Radio**: estaciones en vivo por género (Workout/Rave,
Techno/House, R&B/Soul, Latina, Hip-Hop, Reggae, Chill, Jazz, Rock, Electrónica),
sin publicidad primero —SomaFM y Radio Paradise— y detrás el directorio público de
radio-browser. Nada de esto suma dependencias: la lista la arma api/radio.js.

Tres decisiones que no se ven en la pantalla y son las que hacen que funcione:

- **El audio no pasa por el servidor.** La api entrega la lista y después no ve un
  byte: el teléfono habla con la estación. Sin ancho de banda, sin disco, sin copias.
- **La URL del stream viene resuelta en la lista**, porque iOS sólo deja arrancar
  audio dentro del gesto del toque: cualquier cosa asíncrona entre el dedo y el
  play() es un botón que no hace nada, sin error en ninguna parte.
- **El `<audio>` vive fuera de React** (lib/radio-player.js): un elemento dentro de
  un componente se desmonta con él, y eso es la música cortándose al cambiar de
  pantalla — justo lo que no puede pasar en medio de una serie.

Barra arriba de la barra de pestañas con pausa (deja la estación donde estaba) y
parar; Media Session pone estación, pista y controles en la pantalla bloqueada, y
las canciones siguen con el teléfono en el bolsillo. Qué suena lo dicen SomaFM y
Radio Paradise y nadie más: en el resto la barra muestra la estación en vez de
inventar una pista.

api/test/server-radio.test.js guarda las dos puertas (sesión obligatoria, `src`+`id`
reconstruidos en vez de confiar en el objeto del cliente); RadioBar.test.jsx y el
caso de la fila en Music.test.jsx guardan lo demás.

También: radio.js en el COPY del Dockerfile —importar un archivo que no está copiado
es un contenedor que arranca en ERR_MODULE_NOT_FOUND—, /api/radio y /api/radio/now
(con /api/music/lookup, que faltaba) en la especificación, y docs/RADIO.md.
This commit is contained in:
dsantillan committed 2026-09-23 20:38:19 -04:00
1 parent e1d28f971d
commit 48cf976635
22 files changed
+1662 -15

No files matched your search

+4
View File
@@ -20,6 +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 TimerFlash from './components/TimerFlash.jsx'
import Login from './views/Login.jsx'
import MobileOnboarding from './views/MobileOnboarding.jsx'
@@ -216,6 +217,9 @@ 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 />
<Modals />
<Toast />
<TimerFlash />
+77
View File
@@ -0,0 +1,77 @@
/* 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
@@ -0,0 +1,126 @@
// @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)
})
})
+45
View File
@@ -1117,6 +1117,51 @@ 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. */
.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;
padding:9px 11px;border-radius:var(--r-md);background:var(--glass);border:var(--hair) solid var(--sep-op);
-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}
.mus-rad.on .mus-rad-main{border-color:color-mix(in srgb,var(--acc) 40%,transparent)}
.mus-rad-i{width:34px;height:34px;border-radius:8px;object-fit:cover;flex:0 0 auto}
.mus-rad-i-ph{display:flex;align-items:center;justify-content:center;background:var(--surface-3);color:var(--label-3)}
.mus-rad-i-ph .icn{font-size:16px}
.mus-rad-meta{display:flex;flex-direction:column;min-width:0;flex:1;gap:1px}
.mus-rad-n{font-size:13.5px;font-weight:600;color:var(--label);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.mus-rad-s{font-size:11.5px;color:var(--label-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.mus-rad-go{font-size:17px;color:var(--acc);flex:0 0 auto}
.mus-rad-save{color:var(--label-3)}
.mus-rad-save .icn{font-size:17px}
.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
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{
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);
border-radius:var(--r-lg);padding:9px 12px;
display:flex;align-items:center;gap:10px;
box-shadow:0 12px 34px -8px rgba(0,0,0,.55);
animation:slideup var(--med) var(--ease);
}
body.resting #radio{bottom:calc(190px + var(--sab))}
body.radioing #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))}
}
.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. */
+94
View File
@@ -0,0 +1,94 @@
/* 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 }
+19
View File
@@ -1408,6 +1408,25 @@ 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}',
// radio
'Radio': 'Radio',
'Playing {0}': 'Sonando {0}',
'Paused: {0}': 'En pausa: {0}',
'Playlists': 'Listas',
'Live radio': 'Radio en vivo',
'Play': 'Reproducir',
'Pause': 'Pausar',
'Stop': 'Parar',
'Stations': 'Emisoras',
'no advertising': 'sin publicidad',
'Saved stations': 'Emisoras guardadas',
'{0} stations': '{0} emisoras',
'Loading stations…': 'Cargando emisoras…',
'That station is not answering. Try another one.': 'Esa emisora no está respondiendo. Probá con otra.',
'Save this station': 'Guardar esta emisora',
'Saved to your stations': 'Guardada en tus emisoras',
'Nothing playing. Pick a station below.': 'No hay nada sonando. Elegí una emisora abajo.',
'These are public radio streams: nothing is downloaded, and the audio goes straight from the station to your phone. The first four of each genre are stations with no advertising at all.': 'Son radios públicas: no se descarga nada y el audio va directo de la emisora a tu teléfono. Las primeras de cada género son emisoras sin publicidad.',
'What arrived last': 'Qué llegó en el último envío',
'Datapoints in the last sync': 'Datos en el último envío',
'How they were stamped': 'Cómo vienen marcados',
+20 -2
View File
@@ -35,7 +35,7 @@ export const DEF = {
// somebody else's public playlists (see frontend/src/lib/music.js for the long version), so these
// 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: [] },
music: { user: '', playlists: [], stations: [] },
// 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
@@ -353,7 +353,25 @@ export const useStore = create((set, get) => {
/* 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. */
addPlaylist(item) {
/* Radios saved per profile, next to the playlists: what one person listens to while training is
not what another does, and this document is already per profile and already synced. */
addStation(station) {
if (!station || !station.url) return
update(st => {
const music = st.music || { user: '', playlists: [], stations: [] }
const list = music.stations || []
if (list.some(x => x.src === station.src && x.id === station.id)) return {}
return { music: { ...music, stations: [...list, { src: station.src, id: station.id, name: station.name, url: station.url, genre: station.genre || '', detail: station.detail || '', image: station.image || null }] } }
})
},
removeStation(src, id) {
update(st => {
const music = st.music || { playlists: [], stations: [] }
return { music: { ...music, stations: (music.stations || []).filter(x => !(x.src === src && x.id === id)) } }
})
},
addPlaylist(item) {
if (!item || !item.url) return
// Falls back to the URL for the key rather than refusing the item: this guard used to be
// `if (!item.id) return`, and when the add form forgot to pass one the sheet said "playlist
+37
View File
@@ -2,6 +2,7 @@ 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 { t } from '../lib/i18n.js'
import { deviceId } from '../lib/push.js'
import { useStore } from './useStore.js'
@@ -63,6 +64,7 @@ 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
// 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
@@ -87,6 +89,41 @@ export const useUI = create((set, get) => ({
toastTm = setTimeout(() => set({ toastMsg: '' }), 2200)
},
/* 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. */
playRadio(station, { volume } = {}) {
if (!station || !station.url) return false
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)
return ok
},
toggleRadio() {
const r = get().radio
if (!r) return
if (r.playing) { pauseStream(); set({ radio: { ...r, playing: false } }) }
else { const ok = playStream(r.station.url, r.volume); set({ radio: { ...r, playing: ok } }) }
},
stopRadio() {
pauseStream()
clearMediaSession()
set({ radio: null })
},
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
+98 -3
View File
@@ -16,12 +16,12 @@
* artwork and track count so the list looks like a list, and a page that says nothing leaves the
* card showing the name its owner typed — which is why nothing here depends on it.
*/
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { t } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { t } from '../lib/i18n.js'
import { confirmSheet } from '../sheets.jsx'
import { Button } from '../components/ui.jsx'
import Icon from '../components/Icon.jsx'
@@ -86,6 +86,98 @@ function AddPlaylistSheet({ close }) {
</>
}
/* ---------- radio ----------
*
* 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.
*
* 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
* thousands are mostly commercial broadcasters that may air ads.
*/
function RadioSection() {
const radio = useUI(s => s.radio)
const playRadio = useUI(s => s.playRadio)
const toast = useUI(s => s.toast)
const S = useStore(s => s.S)
const addStation = useStore(s => s.addStation)
const removeStation = useStore(s => s.removeStation)
const [genres, setGenres] = useState(null)
const [genre, setGenre] = useState(null)
const [stations, setStations] = useState(null)
const [busy, setBusy] = useState(false)
/* Logos that did not load. The directory is community-run: a station's `favicon` field is
sometimes a homepage rather than an image, which renders as a broken-image icon mid-list. A
row that fails falls back to the same placeholder as a row that never had one. */
const [noArt, setNoArt] = useState(() => new Set())
const saved = (S.music && S.music.stations) || []
const load = key => {
setBusy(true)
api('/api/radio' + (key ? '?genre=' + encodeURIComponent(key) : ''))
.then(r => {
setGenres(r.genres)
setGenre(r.genre)
setStations(r.stations)
})
.catch(e => toast(e.message))
.finally(() => setBusy(false))
}
useEffect(() => { load(null) }, [])
const play = station => {
// Synchronous on purpose: `play()` has to happen inside this tap for iOS to allow it.
if (!playRadio(station)) toast(t('That station is not answering. Try another one.'))
}
const isSaved = station => saved.some(x => x.src === station.src && x.id === station.id)
const row = station => <div key={station.src + ':' + station.id}
className={'mus-rad' + (radio?.station && radio.station.id === station.id ? ' on' : '')}>
<button className="mus-rad-main" onClick={() => play(station)} aria-label={t('Play')}>
{station.image && !noArt.has(station.image)
? <img className="mus-rad-i" src={station.image} alt=""
onError={() => setNoArt(prev => new Set(prev).add(station.image))} />
: <span className="mus-rad-i mus-rad-i-ph"><Icon name="music" /></span>}
<span className="mus-rad-meta">
<span className="mus-rad-n">{station.name}</span>
<span className="mus-rad-s">{[station.detail, station.genre].filter(Boolean).join(' · ')}</span>
</span>
<Icon name={radio?.station && radio.station.id === station.id && radio.playing ? 'pause' : 'play'} className="mus-rad-go" />
</button>
<button className="iconbtn mus-rad-save" onClick={() => isSaved(station) ? removeStation(station.src, station.id) : (addStation(station), toast(t('Saved to your stations')))}
aria-label={isSaved(station) ? t('Remove') : t('Save this station')}>
<Icon name={isSaved(station) ? 'starFill' : 'star'} />
</button>
</div>
return <>
<h4 className="sec">{t('Radio')}{stations ? <span className="vh-window"> · {t('{0} stations', stations.length)}</span> : null}</h4>
<div className="small dim" style={{ margin: '0 2px 8px', lineHeight: 1.45 }}>
{t('These are public radio streams: nothing is downloaded, and the audio goes straight from the station to your phone. The first four of each genre are stations with no advertising at all.')}
</div>
<div className="chips" style={{ marginBottom: 10 }}>
{(genres || []).map(g => <button key={g.key}
className={'chip' + (genre === g.key ? ' on' : '')}
onClick={() => load(g.key)}>{g.label}</button>)}
</div>
{saved.length > 0 && <>
<div className="mus-sub-h">{t('Saved stations')}</div>
{saved.map(st => row(st))}
</>}
{busy && !stations && <div className="small dim" style={{ margin: '0 2px 10px' }}>{t('Loading stations…')}</div>}
{stations && stations.map(st => row(st))}
{stations && !stations.length && <div className="small dim" style={{ margin: '0 2px 10px' }}>
{t('That station is not answering. Try another one.')}
</div>}
{radio && <div className="small dim" style={{ margin: '8px 2px 0' }}>
{radio.playing ? t('Playing {0}', radio.station.name) : t('Paused: {0}', radio.station.name)}
</div>}
{!radio && <div className="small dim" style={{ margin: '8px 2px 0' }}>{t('Nothing playing. Pick a station below.')}</div>}
</>
}
export default function Music() {
const nav = useNavigate()
const S = useStore(s => s.S)
@@ -130,6 +222,9 @@ export default function Music() {
</div>
</div>}
<RadioSection />
<h4 className="sec">{t('Playlists')}</h4>
{list.length === 0
? <div className="empty">
<div className="ico"><Icon name="music" /></div>
+40
View File
@@ -7,12 +7,23 @@ import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
const nav = vi.fn()
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. */
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: Music } = await import('./Music.jsx')
const { default: Modals } = await import('../components/Modals.jsx')
@@ -23,6 +34,13 @@ let host, root
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
nav.mockClear()
/* The screen now mounts the radio section too, and that one asks the server for the genre list
as soon as it appears. Every test here starts from a server that answers with nothing, and a
test that cares about a request sets its own implementation. */
api.mockReset()
api.mockResolvedValue({ genres: [], genre: null, stations: [] })
playStream.mockClear()
act(() => { useUI.setState({ radio: null }) })
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
@@ -92,6 +110,28 @@ describe('Música', () => {
expect(host.textContent).toContain('Leg Day')
})
/* Radio lives on this screen, and its one non-obvious rule is that the row *is* the play button:
iOS only lets audio start inside the tap that asked for it, so the stream URL arrives with the
station and nothing asynchronous may sit between the finger and the play(). A refactor that
moved the play behind a fetch would look identical and play nothing on an iPhone. */
it('plays a station from its row, inside the same tap', async () => {
const beat = {
src: 'soma', id: 'beatblender', name: 'Beat Blender', genre: 'Electronic',
detail: 'A late night blend', image: null, url: 'https://ice2.somafm.com/beatblender-128-mp3'
}
api.mockResolvedValue({ genres: [{ key: 'techno', label: 'Techno / House' }], genre: 'techno', stations: [beat] })
await mount()
const row = host.querySelector('.mus-rad-main')
expect(row.textContent).toContain('Beat Blender')
expect(row.textContent).toContain('A late night blend · Electronic')
// The chips came from the server too, so the screen never hard-codes the genres it offers.
expect([...host.querySelectorAll('.chips .chip')].map(c => c.textContent)).toEqual(['Techno / House'])
act(() => { row.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(playStream).toHaveBeenCalledWith(beat.url, 1)
expect(useUI.getState().radio.station.id).toBe('beatblender')
expect(useUI.getState().radio.playing).toBe(true)
})
it('saving the same link twice does not duplicate the card', async () => {
useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [] } } }))
act(() => { useStore.getState().addPlaylist(item()) })