diff --git a/frontend/src/stores/soundtrackPlayer.test.ts b/frontend/src/stores/soundtrackPlayer.test.ts index 240b633fe..390e5fd64 100644 --- a/frontend/src/stores/soundtrackPlayer.test.ts +++ b/frontend/src/stores/soundtrackPlayer.test.ts @@ -1,6 +1,7 @@ -import { describe, expect, it } from "vitest"; +import { createPinia, setActivePinia } from "pinia"; +import { describe, expect, it, vi } from "vitest"; import { FRONTEND_RESOURCES_PATH } from "@/utils"; -import { +import useSoundtrackPlayer, { resolveSoundtrackGameArtwork, type SoundtrackArtworkRom, } from "./soundtrackPlayer"; @@ -85,3 +86,37 @@ describe("resolveSoundtrackGameArtwork", () => { expect(resolveSoundtrackGameArtwork(makeRom())).toBeUndefined(); }); }); + +describe("loadPlaylist with preserved shuffle", () => { + function makeTracks(count: number, offset = 0) { + return Array.from({ length: count }, (_, i) => ({ + romId: 1, + fileId: offset + i + 1, + fileName: `track-${offset + i + 1}.mp3`, + url: `/tracks/${offset + i + 1}`, + })); + } + + it("shuffles freshly paged-in tracks instead of appending them in order", () => { + setActivePinia(createPinia()); + const player = useSoundtrackPlayer(); + const firstPage = makeTracks(4); + player.loadPlaylist(firstPage, {}, null); + player.toggleShuffle(); + const shuffledFirstPage = [...player.playlist]; + + const nextPage = makeTracks(4, 4); + // Force the worst shuffle luck: Math.random() = 0 still may not produce + // the identity permutation, so an in-order tail proves the bug. + const randomSpy = vi.spyOn(Math, "random").mockReturnValue(0); + player.loadPlaylist([...firstPage, ...nextPage], {}, null, true); + randomSpy.mockRestore(); + + const ids = (tracks: { fileId: number }[]) => tracks.map((t) => t.fileId); + // The already-shuffled window keeps its order. + expect(ids(player.playlist.slice(0, 4))).toEqual(ids(shuffledFirstPage)); + // The appended window holds the same tracks but not in server order. + expect(ids(player.playlist.slice(4)).sort()).toEqual(ids(nextPage).sort()); + expect(ids(player.playlist.slice(4))).not.toEqual(ids(nextPage)); + }); +}); diff --git a/frontend/src/stores/soundtrackPlayer.ts b/frontend/src/stores/soundtrackPlayer.ts index 286350bb2..06eda4ce8 100644 --- a/frontend/src/stores/soundtrackPlayer.ts +++ b/frontend/src/stores/soundtrackPlayer.ts @@ -168,9 +168,12 @@ const useSoundtrackPlayer = defineStore("soundtrackPlayer", () => { tracksByKey.delete(item.romId + ":" + item.fileId); return [next]; }); + // Tracks not in the previous order (a freshly paged-in window) join + // shuffled too, or playback would turn sequential once the already + // loaded portion of the queue runs out. playlist.value = restored.length > 0 - ? [...restored, ...tracksByKey.values()] + ? [...restored, ...shuffled([...tracksByKey.values()])] : shuffled([...tracksByKey.values()]); return; }