Guardar una emisora no guardaba nada, y las listas la borraban
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

Dos bugs del mismo tipo —silenciosos, y los dos visibles sólo leyendo— en las
estaciones guardadas:

1. `update(mut)` muta el borrador que recibe; el valor de retorno se descarta. La
   primera versión de `addStation` *devolvía* `{ music: … }`, así que la estrella de
   una emisora no hacía absolutamente nada: el aviso decía "guardada", la lista
   seguía vacía y nada en ninguna parte decía por qué.
2. `music` tiene las listas, el usuario de Apple Music **y** estas emisoras. Los
   métodos de listas lo reconstruían con los dos campos que les importaban, así que
   quitar una lista —o escribir tu usuario en Ajustes— tiraba todas las emisoras
   guardadas al piso.

useStore.radio.test.jsx fija las dos (y las dos se comprobaron por mutación: cada
una rompe el test que le toca) y Music.test.jsx recorre el camino entero, de la
estrella al store y de vuelta a la pantalla.

También: la fila de una emisora cae al marcador de posición cuando su logo no
carga —el directorio a veces guarda una página web en el campo del icono, y una
imagen rota se ve peor que ninguna—, y la barra hace lo mismo con la portada.
This commit is contained in:
dsantillan committed 2026-09-23 20:41:36 -04:00
1 parent 48cf976635
commit 8f26b536fd
4 files changed
+145 -22

No files matched your search

+29 -22
View File
@@ -350,28 +350,33 @@ export const useStore = create((set, get) => {
// overwrite, not a change to merge: the push it arms goes without a baseRev.
replaceState(S, push = false) { if (push) forceNext = true; persist(clone(S), push) },
/* 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. Keyed by
source + id for the same reason the playlists are keyed by theirs — starring the same station
twice is one row, and unstarring one never depends on its position in the list. */
addStation(station) {
if (!station || !station.url) return
get().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
st.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) {
get().update(st => {
const music = st.music || { playlists: [], stations: [] }
st.music = { ...music, stations: (music.stations || []).filter(x => !(x.src === src && x.id === id)) }
})
},
/* 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. */
/* 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) {
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
@@ -381,17 +386,19 @@ export const useStore = create((set, get) => {
get().update(s => {
const list = (s.music && s.music.playlists) || []
if (list.some(p => (p.id || p.url) === id)) return
s.music = { user: (s.music && s.music.user) || '', playlists: [...list, { ...item, id }] }
s.music = { ...s.music, user: (s.music && s.music.user) || '', playlists: [...list, { ...item, id }] }
})
},
removePlaylist(id) {
get().update(s => {
const list = (s.music && s.music.playlists) || []
s.music = { user: (s.music && s.music.user) || '', playlists: list.filter(p => p.id !== id) }
// Spread, not a fresh object: `music` also holds the saved radio stations, and rebuilding it
// from two known fields silently dropped them — the star said "saved", the list was empty.
s.music = { ...s.music, user: (s.music && s.music.user) || '', playlists: list.filter(p => p.id !== id) }
})
},
setMusicUser(user) {
get().update(s => { s.music = { user: String(user || '').replace(/^@/, '').trim().slice(0, 40), playlists: (s.music && s.music.playlists) || [] } })
get().update(s => { s.music = { ...s.music, user: String(user || '').replace(/^@/, '').trim().slice(0, 40), playlists: (s.music && s.music.playlists) || [] } })
},
// Fires after the moments where losing local data would actually hurt — a workout just
@@ -0,0 +1,85 @@
// @vitest-environment happy-dom
/* The stations a profile saves, and the neighbours that keep eating them.
*
* Two bugs this pins, both silent, both found by reading rather than by clicking:
*
* 1. `update(mut)` mutates the draft it is handed — the return value is discarded. The first
* version of addStation *returned* `{ music: … }`, so the star on a station did nothing at all:
* the toast said "saved to your stations" and the list stayed empty.
* 2. `music` holds playlists, the Apple Music username *and* these stations. The playlist methods
* rebuilt it from the two fields they cared about, so removing a playlist — or typing a
* username in Settings — dropped every saved station on the floor. Same class of bug as the
* add form that forgot an id: the screen keeps looking right while the data moves on.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../lib/api.js', () => ({ api: vi.fn().mockResolvedValue({}) }))
import { useStore } from './useStore.js'
const station = (over = {}) => ({
src: 'soma', id: 'beatblender', name: 'Beat Blender',
url: 'https://ice2.somafm.com/beatblender-128-mp3',
genre: 'Electronic', detail: 'A late night blend', image: null, ...over
})
const playlist = { id: 'pl.aaa', url: 'https://music.apple.com/us/playlist/leg-day/pl.aaa', kind: 'playlist', name: 'Leg Day' }
const stations = () => useStore.getState().S.music.stations
beforeEach(() => {
useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [], stations: [] } } }))
})
describe('saved radio stations', () => {
it('saves one, with the stream URL, so the row can play without asking again', () => {
useStore.getState().addStation(station())
expect(stations()).toHaveLength(1)
expect(stations()[0]).toMatchObject({ src: 'soma', id: 'beatblender', name: 'Beat Blender' })
expect(stations()[0].url).toBe('https://ice2.somafm.com/beatblender-128-mp3')
})
it('starring the same station twice is one row', () => {
useStore.getState().addStation(station())
useStore.getState().addStation(station({ name: 'Beat Blender (again)' }))
expect(stations()).toHaveLength(1)
expect(stations()[0].name).toBe('Beat Blender')
})
it('refuses a station with no stream, which would be a row that cannot play', () => {
useStore.getState().addStation(station({ url: null }))
useStore.getState().addStation(null)
expect(stations()).toHaveLength(0)
})
it('unstars the one it was asked about, and only that one', () => {
useStore.getState().addStation(station())
useStore.getState().addStation(station({ src: 'paradise', id: 'mellow', name: 'Radio Paradise Mellow' }))
useStore.getState().removeStation('soma', 'beatblender')
expect(stations().map(s => s.id)).toEqual(['mellow'])
})
it('survives a state that predates the feature, where music has no stations at all', () => {
useStore.setState(s => ({ S: { ...s.S, music: { user: 'ana', playlists: [] } } }))
useStore.getState().addStation(station())
expect(stations()).toHaveLength(1)
expect(useStore.getState().S.music.user).toBe('ana')
})
/* The playlists screen and Settings both rebuild `music`; the stations have to come out the other
side of that. */
it('is not dropped by the playlist mutations that share the same object', () => {
useStore.getState().addStation(station())
useStore.getState().addPlaylist(playlist)
expect(stations()).toHaveLength(1)
useStore.getState().removePlaylist('pl.aaa')
expect(useStore.getState().S.music.playlists).toHaveLength(0)
expect(stations()).toHaveLength(1)
useStore.getState().setMusicUser('@ana')
expect(useStore.getState().S.music.user).toBe('ana')
expect(stations()).toHaveLength(1)
useStore.getState().addPlaylist(playlist)
expect(stations()).toHaveLength(1)
})
})
+4
View File
@@ -110,6 +110,10 @@ export const useUI = create((set, get) => ({
clearMediaSession()
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
setStreamVolume(volume)
+27
View File
@@ -132,6 +132,33 @@ describe('Música', () => {
expect(useUI.getState().radio.playing).toBe(true)
})
/* The star, all the way to the store and back on screen. It was a no-op for a while: the store
method *returned* the new `music` object and `update()` only reads mutations, so the toast
appeared, the list stayed empty, and nothing said why. */
it('saves a station with the star, and it comes back as a saved row', 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: [], genre: 'workout', stations: [beat] })
await mount()
const star = host.querySelector('.mus-rad-save')
expect(star.getAttribute('aria-label')).toBe('Save this station')
act(() => { star.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useStore.getState().S.music.stations.map(s => s.id)).toEqual(['beatblender'])
expect(host.textContent).toContain('Saved stations')
// Starred, so the same button now offers to take it away — and the row is on screen twice:
// once in the saved block, once in the genre list.
expect(host.querySelectorAll('.mus-rad-save')[0].getAttribute('aria-label')).toBe('Remove')
expect(host.querySelectorAll('.mus-rad').length).toBe(2)
act(() => { host.querySelectorAll('.mus-rad-save')[0].dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useStore.getState().S.music.stations).toEqual([])
expect(host.textContent).not.toContain('Saved stations')
})
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()) })