feat(web): player queue store

- queue with next, previous, seek, repeat (off, all, one), shuffle that keeps the original order, enqueue, play next and remove
- seek and restart requests are explicit, so the audio engine can follow them
This commit is contained in:
tgiachi 2026-11-12 11:24:55 +01:00
commit cffa8f1976
2 changed files with 467 additions and 0 deletions

View file

@ -0,0 +1,285 @@
import { beforeEach, expect, test } from 'vitest'
import type { Track } from '@/api/catalog'
import { currentTrack, setRandom, usePlayer } from './store'
function track(n: number, durationMs = 200_000): Track {
return {
id: n,
title: `t${n}`,
duration_ms: durationMs,
track_no: n,
disc_no: 1,
album: { id: 1, title: 'Album' },
artists: [{ id: 1, name: 'Artist' }],
format: 'flac',
}
}
const [t1, t2, t3, t4, t5] = [1, 2, 3, 4, 5].map((n) => track(n))
const all = [t1, t2, t3, t4, t5]
const ids = () => usePlayer.getState().queue.map((t) => t.id)
const current = () => currentTrack(usePlayer.getState())
beforeEach(() => {
usePlayer.setState({
queue: [],
original: [],
index: 0,
playing: false,
positionMs: 0,
shuffle: false,
repeat: 'off',
seekMs: null,
seekId: 0,
})
setRandom(() => 0)
})
test('playTracks fills the queue and starts the first track', () => {
usePlayer.getState().playTracks(all)
expect(ids()).toEqual([1, 2, 3, 4, 5])
expect(current()).toBe(t1)
expect(usePlayer.getState().playing).toBe(true)
})
test('playTracks can start from any track', () => {
usePlayer.getState().playTracks(all, 2)
expect(current()).toBe(t3)
expect(ids()).toEqual([1, 2, 3, 4, 5])
})
test('playTracks with nothing to play leaves an empty, stopped queue', () => {
usePlayer.getState().playTracks([], 0)
expect(ids()).toEqual([])
expect(current()).toBeNull()
expect(usePlayer.getState().playing).toBe(false)
})
test('togglePlay does nothing with an empty queue and flips play and pause otherwise', () => {
usePlayer.getState().togglePlay()
expect(usePlayer.getState().playing).toBe(false)
usePlayer.getState().playTracks(all)
usePlayer.getState().togglePlay()
expect(usePlayer.getState().playing).toBe(false)
usePlayer.getState().togglePlay()
expect(usePlayer.getState().playing).toBe(true)
})
test('next goes to the following track and plays it', () => {
usePlayer.getState().playTracks(all)
usePlayer.getState().togglePlay() // paused
usePlayer.getState().tick(5000)
usePlayer.getState().next()
expect(current()).toBe(t2)
expect(usePlayer.getState().playing).toBe(true)
expect(usePlayer.getState().positionMs).toBe(0)
})
test('next at the end stops when repeat is off and keeps the last track', () => {
usePlayer.getState().playTracks(all, 4)
usePlayer.getState().next()
expect(current()).toBe(t5)
expect(usePlayer.getState().playing).toBe(false)
expect(usePlayer.getState().positionMs).toBe(0)
})
test('next at the end wraps to the first track when repeat is all', () => {
usePlayer.getState().playTracks(all, 4)
usePlayer.getState().cycleRepeat() // all
usePlayer.getState().next()
expect(current()).toBe(t1)
expect(usePlayer.getState().playing).toBe(true)
})
test('previous restarts the track when more than three seconds have played', () => {
usePlayer.getState().playTracks(all, 2)
usePlayer.getState().tick(3001)
const before = usePlayer.getState().seekId
usePlayer.getState().prev()
expect(current()).toBe(t3)
expect(usePlayer.getState().positionMs).toBe(0)
expect(usePlayer.getState().seekMs).toBe(0)
expect(usePlayer.getState().seekId).toBe(before + 1)
})
test('previous within the first three seconds goes back one track', () => {
usePlayer.getState().playTracks(all, 2)
usePlayer.getState().tick(3000)
usePlayer.getState().prev()
expect(current()).toBe(t2)
expect(usePlayer.getState().playing).toBe(true)
})
test('previous on the first track restarts it', () => {
usePlayer.getState().playTracks(all)
usePlayer.getState().tick(1000)
const before = usePlayer.getState().seekId
usePlayer.getState().prev()
expect(current()).toBe(t1)
expect(usePlayer.getState().seekId).toBe(before + 1)
expect(usePlayer.getState().positionMs).toBe(0)
})
test('a track that ends moves on to the next one', () => {
usePlayer.getState().playTracks(all)
usePlayer.getState().trackEnded()
expect(current()).toBe(t2)
})
test('a track that ends with repeat one plays again from the start', () => {
usePlayer.getState().playTracks(all, 1)
usePlayer.getState().cycleRepeat()
usePlayer.getState().cycleRepeat() // one
const before = usePlayer.getState().seekId
usePlayer.getState().trackEnded()
expect(current()).toBe(t2)
expect(usePlayer.getState().playing).toBe(true)
expect(usePlayer.getState().seekMs).toBe(0)
expect(usePlayer.getState().seekId).toBe(before + 1)
})
test('a last track that ends with repeat off stops the player', () => {
usePlayer.getState().playTracks(all, 4)
usePlayer.getState().trackEnded()
expect(usePlayer.getState().playing).toBe(false)
})
test('repeat goes off, all, one and back to off', () => {
const seen = [usePlayer.getState().repeat]
for (let i = 0; i < 3; i++) {
usePlayer.getState().cycleRepeat()
seen.push(usePlayer.getState().repeat)
}
expect(seen).toEqual(['off', 'all', 'one', 'off'])
})
test('seek stores the position and asks the engine to move', () => {
usePlayer.getState().playTracks(all)
usePlayer.getState().seek(42_000)
expect(usePlayer.getState().positionMs).toBe(42_000)
expect(usePlayer.getState().seekMs).toBe(42_000)
expect(usePlayer.getState().seekId).toBe(1)
})
test('seek never goes below zero or past the end of the track', () => {
usePlayer.getState().playTracks([track(9, 60_000)])
usePlayer.getState().seek(-5)
expect(usePlayer.getState().positionMs).toBe(0)
usePlayer.getState().seek(90_000)
expect(usePlayer.getState().positionMs).toBe(60_000)
})
test('tick follows the audio without asking the engine to move', () => {
usePlayer.getState().playTracks(all)
usePlayer.getState().tick(1234)
expect(usePlayer.getState().positionMs).toBe(1234)
expect(usePlayer.getState().seekId).toBe(0)
})
test('enqueue adds to the end and playNext right after the current track', () => {
usePlayer.getState().playTracks([t1, t2, t3], 1)
usePlayer.getState().enqueue(t5)
usePlayer.getState().playNext(t4)
expect(ids()).toEqual([1, 2, 4, 3, 5])
expect(current()).toBe(t2)
})
test('playNext on an empty queue makes the track the only one', () => {
usePlayer.getState().playNext(t3)
expect(ids()).toEqual([3])
expect(current()).toBe(t3)
expect(usePlayer.getState().playing).toBe(false)
})
test('removing a track before the current one keeps the current track playing', () => {
usePlayer.getState().playTracks(all, 3)
usePlayer.getState().removeAt(0)
expect(ids()).toEqual([2, 3, 4, 5])
expect(current()).toBe(t4)
})
test('removing a track after the current one leaves the current track alone', () => {
usePlayer.getState().playTracks(all, 1)
usePlayer.getState().removeAt(3)
expect(ids()).toEqual([1, 2, 3, 5])
expect(current()).toBe(t2)
})
test('removing the current track plays the one that followed it', () => {
usePlayer.getState().playTracks(all, 1)
usePlayer.getState().tick(9000)
usePlayer.getState().removeAt(1)
expect(ids()).toEqual([1, 3, 4, 5])
expect(current()).toBe(t3)
expect(usePlayer.getState().playing).toBe(true)
expect(usePlayer.getState().positionMs).toBe(0)
})
test('removing the current track when it is the last one stops the player', () => {
usePlayer.getState().playTracks([t1, t2], 1)
usePlayer.getState().removeAt(1)
expect(ids()).toEqual([1])
expect(current()).toBe(t1)
expect(usePlayer.getState().playing).toBe(false)
})
test('removing the only track empties the queue and stops', () => {
usePlayer.getState().playTracks([t1])
usePlayer.getState().removeAt(0)
expect(ids()).toEqual([])
expect(current()).toBeNull()
expect(usePlayer.getState().playing).toBe(false)
})
test('removing a position that does not exist changes nothing', () => {
usePlayer.getState().playTracks(all)
usePlayer.getState().removeAt(9)
usePlayer.getState().removeAt(-1)
expect(ids()).toEqual([1, 2, 3, 4, 5])
})
test('turning shuffle on reorders only the tracks after the current one', () => {
usePlayer.getState().playTracks(all, 1)
usePlayer.getState().toggleShuffle()
// with a random source that always answers 0 the rest [3,4,5] becomes [4,5,3]
expect(ids()).toEqual([1, 2, 4, 5, 3])
expect(current()).toBe(t2)
expect(usePlayer.getState().shuffle).toBe(true)
})
test('turning shuffle off restores the original order around the current track', () => {
usePlayer.getState().playTracks(all, 0)
usePlayer.getState().toggleShuffle()
usePlayer.getState().next() // now on the second track of the shuffled order
const playing = current()!
usePlayer.getState().toggleShuffle()
expect(ids()).toEqual([1, 2, 3, 4, 5])
expect(current()).toBe(playing)
expect(usePlayer.getState().shuffle).toBe(false)
})
test('shuffle on and straight off gives back the same queue', () => {
usePlayer.getState().playTracks(all, 2)
usePlayer.getState().toggleShuffle()
usePlayer.getState().toggleShuffle()
expect(ids()).toEqual([1, 2, 3, 4, 5])
expect(current()).toBe(t3)
})
test('a track added while shuffled is kept in the original order when shuffle is turned off', () => {
usePlayer.getState().playTracks([t1, t2, t3], 0)
usePlayer.getState().toggleShuffle()
usePlayer.getState().enqueue(t4)
usePlayer.getState().toggleShuffle()
expect(ids()).toEqual([1, 2, 3, 4])
})
test('with shuffle on, playTracks starts at the chosen track and shuffles the rest', () => {
usePlayer.getState().toggleShuffle()
usePlayer.getState().playTracks(all, 2)
expect(current()).toBe(t3)
expect(usePlayer.getState().index).toBe(0)
expect(ids().slice().sort()).toEqual([1, 2, 3, 4, 5])
expect(ids()[0]).toBe(3)
})

182
web/src/player/store.ts Normal file
View file

@ -0,0 +1,182 @@
import { create } from 'zustand'
import type { Track } from '@/api/catalog'
export type Repeat = 'off' | 'all' | 'one'
export interface PlayerState {
queue: Track[]
index: number
playing: boolean
positionMs: number
shuffle: boolean
repeat: Repeat
/** The queue in its own order, kept while it is shuffled so that turning shuffle off can restore it. */
original: Track[]
/** The audio engine moves to `seekMs` whenever `seekId` changes. */
seekMs: number | null
seekId: number
/** Changes every time a new list is started, so that playing the same track again restarts it. */
playId: number
playTracks(tracks: Track[], start?: number): void
togglePlay(): void
next(): void
prev(): void
trackEnded(): void
seek(ms: number): void
tick(positionMs: number): void
enqueue(track: Track): void
playNext(track: Track): void
removeAt(i: number): void
toggleShuffle(): void
cycleRepeat(): void
}
let random: () => number = Math.random
/** Tests replace the random source to get a known shuffle. */
export function setRandom(fn: () => number): void {
random = fn
}
/** Fisher–Yates on a copy. */
function shuffled<T>(items: T[]): T[] {
const out = items.slice()
for (let i = out.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1))
;[out[i], out[j]] = [out[j], out[i]]
}
return out
}
export function currentTrack(state: Pick<PlayerState, 'queue' | 'index'>): Track | null {
return state.queue[state.index] ?? null
}
/** The fields that make the engine start the current track over. */
const restart = (s: PlayerState) => ({ positionMs: 0, seekMs: 0, seekId: s.seekId + 1 })
const RESTART_AFTER_MS = 3000
export const usePlayer = create<PlayerState>()((set, get) => ({
queue: [],
index: 0,
playing: false,
positionMs: 0,
shuffle: false,
repeat: 'off',
original: [],
seekMs: null,
seekId: 0,
playId: 0,
playTracks(tracks, start = 0) {
set((s) => {
if (tracks.length === 0) {
return { queue: [], original: [], index: 0, playing: false, positionMs: 0, playId: s.playId + 1 }
}
const i = Math.min(Math.max(start, 0), tracks.length - 1)
const queue = s.shuffle ? [tracks[i], ...shuffled(tracks.filter((_, k) => k !== i))] : tracks
return {
queue,
original: tracks,
index: s.shuffle ? 0 : i,
playing: true,
positionMs: 0,
playId: s.playId + 1,
}
})
},
togglePlay() {
set((s) => (currentTrack(s) ? { playing: !s.playing } : s))
},
next() {
set((s) => {
if (s.queue.length === 0) return s
if (s.index < s.queue.length - 1) return { index: s.index + 1, playing: true, positionMs: 0 }
if (s.repeat === 'all') {
return { index: 0, playing: true, positionMs: 0, ...(s.index === 0 ? restart(s) : {}) }
}
return { playing: false, ...restart(s) }
})
},
prev() {
set((s) => {
if (s.queue.length === 0) return s
if (s.positionMs > RESTART_AFTER_MS || s.index === 0) return restart(s)
return { index: s.index - 1, playing: true, positionMs: 0 }
})
},
trackEnded() {
const s = get()
if (s.repeat === 'one' && currentTrack(s)) set({ playing: true, ...restart(s) })
else s.next()
},
seek(ms) {
set((s) => {
const duration = currentTrack(s)?.duration_ms ?? 0
const clamped = Math.max(0, duration > 0 ? Math.min(ms, duration) : ms)
return { positionMs: clamped, seekMs: clamped, seekId: s.seekId + 1 }
})
},
tick(positionMs) {
set({ positionMs })
},
enqueue(track) {
set((s) => ({ queue: [...s.queue, track], original: [...s.original, track] }))
},
playNext(track) {
set((s) => {
if (s.queue.length === 0) return { queue: [track], original: [track], index: 0 }
const queue = s.queue.slice()
queue.splice(s.index + 1, 0, track)
const original = s.original.slice()
const at = original.indexOf(currentTrack(s)!)
original.splice(at + 1, 0, track)
return { queue, original }
})
},
removeAt(i) {
set((s) => {
if (i < 0 || i >= s.queue.length) return s
const removed = s.queue[i]
const queue = s.queue.filter((_, k) => k !== i)
const original = s.original.slice()
const at = original.indexOf(removed)
if (at >= 0) original.splice(at, 1)
if (queue.length === 0) return { queue, original, index: 0, playing: false, positionMs: 0 }
if (i < s.index) return { queue, original, index: s.index - 1 }
if (i > s.index) return { queue, original }
// The current track was removed: the one that followed it is now at the same position.
if (i < queue.length) return { queue, original, playing: true, positionMs: 0 }
return { queue, original, index: queue.length - 1, playing: false, positionMs: 0 }
})
},
toggleShuffle() {
set((s) => {
if (!s.shuffle) {
const queue = [...s.queue.slice(0, s.index + 1), ...shuffled(s.queue.slice(s.index + 1))]
return { shuffle: true, queue, original: s.queue.slice() }
}
const now = currentTrack(s)
const found = now ? s.original.indexOf(now) : -1
const index = found >= 0 ? found : Math.min(s.index, Math.max(s.original.length - 1, 0))
return { shuffle: false, queue: s.original.slice(), index }
})
},
cycleRepeat() {
set((s) => ({ repeat: s.repeat === 'off' ? 'all' : s.repeat === 'all' ? 'one' : 'off' }))
},
}))