diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 39d4554..9bae2c7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -37,7 +37,8 @@ The workspace contains the root app (`src/`, `tests/`) and `@libras/website` (`w | `Network` / `SubsonicClient` | Connection cancellation, normalized domain access / Subsonic protocol requests | | `Cache` | Account-scoped library, queue, images, downloads, playlists, and OPFS persistence | | `Playback` | Queue commands, server synchronization, and playback orchestration | -| `AudioPlayer` | Audio transport, seeking, keyboard shortcuts, and Media Session | +| `AudioTransport` | Native audio lifetime, source acquisition, reactive transport state, and seeking | +| `AudioPlayer` | Headless keyboard shortcuts and Media Session binding to the app-owned transport | | `Covers` / `TrackEngine` | Resource acquisition, download scheduling, and browser URL lifetimes | | `Playlists` | Server-confirmed playlist operations and conflict detection; no offline outbox | | `Router` | Query routes, native fragment anchors, active navigation metadata, and optional view transitions | diff --git a/src/_search.svelte b/src/_search.svelte index 63ad754..097d40c 100644 --- a/src/_search.svelte +++ b/src/_search.svelte @@ -3,6 +3,26 @@ import type { Album, Artist, Track } from "./schema"; import type { Immutable } from "./cache.svelte"; + export const searchTypes = ["artist", "album", "track"] as const; + export type SearchType = (typeof searchTypes)[number]; + + export function parseSearch(parameters: URLSearchParams) { + const selected = parameters.getAll("type"); + return { + query: parameters.get("q") ?? "", + types: searchTypes.filter((type) => selected.includes(type)), + }; + } + + /** Keep the route bare; encode only search criteria, never the full parameter collection. */ + export function searchHref(query = "", types: readonly SearchType[] = []) { + const parameters = new URLSearchParams(); + for (const type of searchTypes) if (types.includes(type)) parameters.append("type", type); + if (query) parameters.set("q", query); + const suffix = parameters.toString(); + return `?/search${suffix ? `&${suffix}` : ""}`; + } + const searchGroups = ["Artists", "Albums", "Tracks"] as const; type SearchGroup = (typeof searchGroups)[number]; @@ -16,12 +36,6 @@ artworkId?: string; } - export function createSearchState() { - return { query: "", limits: { Artists: 3, Albums: 3, Tracks: 3 } }; - } - - type SearchState = ReturnType; - function availableTrackIds( tracks: readonly Immutable[], isAvailable: (id: string) => boolean, @@ -87,6 +101,7 @@ keys: ["title", "artist", "album"], }); return { + records, Artists: snapshot("Artists"), Albums: snapshot("Albums"), Tracks: snapshot("Tracks"), @@ -94,7 +109,11 @@ }; } - export function searchLibrary(index: ReturnType, query: string) { + export function searchLibrary( + index: ReturnType, + query: string, + browse = false, + ) { query = query.trim().replace(/\s+/g, " "); const groups = searchGroups.map((group) => { // Retrieve matches explicitly without a library limit so equal scores can be @@ -113,8 +132,8 @@ : []; return { group, - total: matches.length, - records: matches.map((result) => result.obj), + total: !query && browse ? index.records[group].length : matches.length, + records: !query && browse ? index.records[group] : matches.map((result) => result.obj), }; }); return { query, groups }; @@ -123,6 +142,8 @@ = 0 && cache.queue.position > 0)} hasNext={hasNextTrack} onprevious={() => playback.previous()} onnext={() => playback.next()} - onposition={(position) => playback.setPosition(position)} - onended={() => playback.ended()} - onstatechange={(state) => playback.updatePlayerState(state)} /> {#snippet settingsRoute()} @@ -161,7 +154,7 @@ {#snippet searchRoute()} - + {/snippet} {#snippet artistRoute(params: RouteParams)} @@ -173,7 +166,7 @@ {session} {playback} {appName} - playbackState={playbackLoading ? "loading" : player?.playing ? "playing" : "paused"} + playbackState={playbackLoading ? "loading" : player.playing ? "playing" : "paused"} /> {/snippet} @@ -186,7 +179,7 @@ {session} {playback} {appName} - playbackState={playbackLoading ? "loading" : player?.playing ? "playing" : "paused"} + playbackState={playbackLoading ? "loading" : player.playing ? "playing" : "paused"} /> {/snippet} diff --git a/src/audio-player.svelte b/src/audio-player.svelte index a9a001c..8d9556f 100644 --- a/src/audio-player.svelte +++ b/src/audio-player.svelte @@ -1,146 +1,36 @@ - - diff --git a/src/audio-transport.svelte.ts b/src/audio-transport.svelte.ts new file mode 100644 index 0000000..0fbf642 --- /dev/null +++ b/src/audio-transport.svelte.ts @@ -0,0 +1,420 @@ +export type PlaybackStatus = + | "idle" + | "loading" + | "ready" + | "buffering" + | "seeking" + | "ended" + | "error"; +export interface PlayerState { + readonly status: PlaybackStatus; + readonly playing: boolean; +} +export interface PlayerSource { + url: string; + offset?: number; + /** full: any position; seekable: browser ranges; buffered: buffered ranges only. */ + seekMode: "full" | "seekable" | "buffered"; + /** Owns only this result. Called once when replaced, unloaded, or returned too late. */ + release(): void; +} +export interface PlayerTrack { + metadata: { + title: string; + artist?: string; + album?: string; + /** May be a reactive getter; text metadata is snapshotted at play time. */ + readonly artwork?: string; + duration?: number; + }; + position?: number; + /** Abort cancels acquisition, not a returned source's lifetime. Late results + * must own independent cleanup, never a newer result's resources. */ + getSource(options: { + position: number; + forceTranscode: boolean; + signal: AbortSignal; + }): Promise; +} +export interface TransportCallbacks { + onposition?: (seconds: number) => void; + onended?: () => void; + onstatechange?: (state: PlayerState) => void; +} + +/** One native audio element. Create on the client; dispose independently of any + * presentation or browser-control binding. Commands settle failures in state. */ +export class AudioTransport { + #audio: HTMLAudioElement | undefined; + #callbacks: TransportCallbacks; + #track = $state.raw(); + #source: PlayerSource | undefined; + #position = $state(0); + #measuredDuration = $state(0); + #playing = $state(false); + #status = $state("idle"); + #error = $state.raw(); + #intent = false; + #forced = false; + #generation = 0; + #abort: AbortController | undefined; + #publishedState: PlayerState = { status: "idle", playing: false }; + #removeEvents: () => void; + #rate = $state(1); + #disposed = false; + + get position() { + return this.#position; + } + get duration() { + return this.#measuredDuration > 0 + ? this.#measuredDuration + : (this.#track?.metadata.duration ?? 0); + } + get playing() { + return this.#playing; + } + get status() { + return this.#status; + } + get error() { + return this.#error; + } + get metadata(): Readonly | undefined { + return this.#track?.metadata; + } + get playbackRate() { + return this.#rate; + } + + constructor(callbacks: TransportCallbacks = {}) { + this.#callbacks = callbacks; + const element = new Audio(); + this.#audio = element; + element.preload = "metadata"; + const onTime = () => { + if (!this.#track || !element.currentSrc) return; + this.#setPosition( + (this.#source?.offset ?? 0) + + (Number.isFinite(element.currentTime) ? element.currentTime : 0), + ); + }; + const onMetadata = () => { + if (!this.#track || !element.currentSrc) return; + const offset = this.#source?.offset ?? 0; + this.#measuredDuration = + offset > 0 + ? (this.#track.metadata.duration ?? + (Number.isFinite(element.duration) ? offset + element.duration : 0)) + : Number.isFinite(element.duration) + ? element.duration + : 0; + }; + const events: Record void> = { + timeupdate: onTime, + loadedmetadata: onMetadata, + durationchange: onMetadata, + ratechange: () => { + this.#rate = element.playbackRate; + }, + playing: () => { + if (!this.#intent) { + element.pause(); + return; + } + this.#playing = true; + this.#status = "ready"; + this.#publishState(); + }, + pause: () => { + if (!element.paused || !this.#playing) return; + this.#playing = false; + this.#publishState(); + }, + waiting: () => { + if (this.#intent && this.status === "ready") this.#status = "buffering"; + this.#publishState(); + }, + canplay: () => { + if (this.status === "buffering") this.#status = "ready"; + this.#publishState(); + }, + ended: () => { + if (!element.currentSrc || !this.#intent) return; + this.#intent = false; + this.#playing = false; + this.#status = "ended"; + this.#publishState(); + this.#callbacks.onended?.(); + }, + error: () => { + if (!element.currentSrc || this.status === "loading" || this.status === "seeking") return; + if (element.error?.code === 4 && !this.#forced) + void this.#load(this.position, this.#intent, true); + else this.#fail(new Error(element.error?.message || "The track could not be played.")); + }, + }; + for (const [event, handler] of Object.entries(events)) element.addEventListener(event, handler); + this.#removeEvents = () => { + for (const [event, handler] of Object.entries(events)) + element.removeEventListener(event, handler); + }; + } + + #publishState() { + if ( + this.#publishedState.status === this.status && + this.#publishedState.playing === this.playing + ) + return; + this.#publishedState = { status: this.status, playing: this.playing }; + this.#callbacks.onstatechange?.(this.#publishedState); + } + #pauseAudio() { + // Internal transitions publish their final state, not an intermediate native pause. + this.#playing = false; + this.#audio?.pause(); + } + #setPosition(seconds: number) { + this.#position = seconds; + this.#callbacks.onposition?.(seconds); + } + #release(result: PlayerSource | undefined) { + try { + result?.release(); + } catch { + /* Provider cleanup must not prevent replacement or teardown. */ + } + } + #clearSource() { + this.#audio?.removeAttribute("src"); + this.#audio?.load(); + const previous = this.#source; + this.#source = undefined; + this.#release(previous); + } + #invalidate() { + this.#generation++; + this.#abort?.abort(); + this.#abort = undefined; + } + #fail(cause: unknown) { + this.#invalidate(); + this.#intent = false; + this.#pauseAudio(); + this.#error = cause; + this.#status = "error"; + this.#publishState(); + } + #metadata(element: HTMLAudioElement, signal: AbortSignal) { + if (element.readyState >= 1) return Promise.resolve(); + return new Promise((resolve, reject) => { + const cleanup = () => { + element.removeEventListener("loadedmetadata", loaded); + element.removeEventListener("error", failed); + signal.removeEventListener("abort", aborted); + }; + const loaded = () => { + cleanup(); + resolve(); + }; + const failed = () => { + cleanup(); + reject(new DOMException("The audio format is unsupported.", "NotSupportedError")); + }; + const aborted = () => { + cleanup(); + reject(new DOMException("Playback cancelled.", "AbortError")); + }; + element.addEventListener("loadedmetadata", loaded); + element.addEventListener("error", failed); + signal.addEventListener("abort", aborted, { once: true }); + if (signal.aborted) aborted(); + }); + } + async #load(position: number, autoplay: boolean, forceTranscode = false, seeking = false) { + const element = this.#audio; + const current = this.#track; + if (!element || !current) return; + this.#invalidate(); + this.#pauseAudio(); + this.#clearSource(); + const request = this.#generation; + const controller = new AbortController(); + this.#abort = controller; + this.#intent = autoplay; + this.#error = undefined; + this.#status = seeking ? "seeking" : "loading"; + const valid = () => !this.#disposed && request === this.#generation && this.#audio === element; + this.#publishState(); + if (!valid()) return; + this.#setPosition(position); + if (!valid()) return; + const prepare = async (transcode: boolean) => { + const nextSource = await current.getSource({ + forceTranscode: transcode, + position, + signal: controller.signal, + }); + if (!valid()) { + this.#release(nextSource); + return; + } + this.#source = nextSource; + const offset = nextSource.offset ?? 0; + this.#measuredDuration = 0; + this.#forced = transcode || offset > 0; + element.src = nextSource.url; + if (position > 0) { + await this.#metadata(element, controller.signal); + if (!valid()) return; + element.currentTime = Math.min( + Math.max(0, position - offset), + Number.isFinite(element.duration) ? element.duration : position, + ); + const actualPosition = offset + element.currentTime; + if (actualPosition !== position) this.#setPosition(actualPosition); + if (!valid()) return; + } + if (autoplay && this.#intent) await element.play(); + if (!valid()) return; + this.#status = "ready"; + this.#playing = !element.paused; + this.#publishState(); + }; + try { + try { + await prepare(forceTranscode); + } catch (error) { + if (!valid()) return; + if ( + forceTranscode || + !(error instanceof Error) || + !(error.name === "NotSupportedError" || /supported sources/i.test(error.message)) + ) + throw error; + this.#clearSource(); + await prepare(true); + } + } catch (error) { + if (valid()) this.#fail(error); + } + } + + /** Start fresh. Resolution means settled (including cancellation), not success. + * Commands after disposal are no-ops. */ + async play(next: PlayerTrack) { + if (this.#disposed || !this.#audio) return; + this.#unload(); + if (this.#disposed) return; + this.#track = { + ...next, + metadata: { + ...next.metadata, + get artwork() { + return next.metadata.artwork; + }, + }, + }; + this.#position = Number.isFinite(next.position) ? Math.max(0, next.position ?? 0) : 0; + await this.#load(this.position, true); + } + /** Resume, restart after end, or retry after error; same settlement as play(). */ + async resume() { + if (this.#disposed || !this.#audio || !this.#track) return; + if (this.status === "loading" || this.status === "seeking") { + await this.#load(this.position, true, this.#forced, this.status === "seeking"); + return; + } + // Native currentSrc may still name a retired resource after removeAttribute/load. + if ( + !this.#source || + !this.#audio.currentSrc || + this.status === "error" || + this.status === "ended" + ) { + await this.#load(this.status === "ended" ? 0 : this.position, true); + return; + } + this.#intent = true; + const request = this.#generation; + try { + await this.#audio.play(); + } catch (error) { + if (request === this.#generation) this.#fail(error); + } + } + pause() { + if (this.#disposed || !this.#audio) return; + this.#invalidate(); + this.#intent = false; + this.#pauseAudio(); + if (this.status === "loading" || this.status === "seeking") this.#clearSource(); + if (this.status !== "ended" && this.status !== "error") + this.#status = this.#track ? "ready" : "idle"; + this.#publishState(); + } + /** Seek in full-track seconds, preserving play/pause intent. */ + async seek(target: number) { + if (this.#disposed || !Number.isFinite(target) || !this.#audio || !this.#track) return; + target = Math.max(0, this.duration > 0 ? Math.min(target, this.duration) : target); + const element = this.#audio; + const offset = this.#source?.offset ?? 0; + const seekMode = this.#source?.seekMode ?? "buffered"; + const contains = (ranges: TimeRanges) => { + const relative = target - offset; + for (let i = 0; i < ranges.length; i++) + if (relative >= ranges.start(i) && relative <= ranges.end(i)) return true; + return false; + }; + const buffered = contains(element.buffered); + const seekable = seekMode === "seekable" && contains(element.seekable); + if ( + element.currentSrc && + (seekMode === "full" || buffered || seekable) && + this.status !== "loading" && + this.status !== "seeking" + ) { + try { + element.currentTime = target - offset; + this.#setPosition(target); + return; + } catch (error) { + if (seekMode === "full") { + this.#fail(error); + return; + } + } + } + await this.#load(target, this.#intent, false, true); + } + /** Background Space uses intent even before the first source arrives. */ + toggle() { + if (!this.#track) return; + if (this.#intent) this.pause(); + else void this.resume(); + } + unload() { + this.#unload(); + } + #unload() { + this.#invalidate(); + this.#intent = false; + this.#pauseAudio(); + this.#clearSource(); + this.#forced = false; + this.#measuredDuration = 0; + this.#status = "idle"; + this.#track = undefined; + this.#position = 0; + this.#error = undefined; + this.#publishState(); + } + dispose() { + if (this.#disposed) return; + this.#disposed = true; + this.#removeEvents(); + this.unload(); + this.#audio = undefined; + } +} diff --git a/src/playback.svelte.ts b/src/playback.svelte.ts index 75ae5a7..47101c5 100644 --- a/src/playback.svelte.ts +++ b/src/playback.svelte.ts @@ -2,8 +2,7 @@ import { getAccountKey } from "./auth"; import type { Covers } from "./covers.svelte"; import type { Cache, CachedQueue, CacheSelection, Immutable } from "./cache.svelte"; import type { QueueConnection, RemoteQueue } from "./network.svelte"; -import type AudioPlayer from "./audio-player.svelte"; -import type { PlayerState, PlayerTrack } from "./audio-player.svelte"; +import type { AudioTransport, PlayerState, PlayerTrack } from "./audio-transport.svelte"; import type { TrackEngine } from "./track.svelte"; type PlaybackActivity = "active" | "paused" | "inactive"; @@ -51,13 +50,13 @@ function toRemoteQueue(local: Immutable): RemoteQueue { }; } -/** Owns queue commands, Player coordination and server synchronization. - * Cache remains the authoritative queue and owns local durability; Player owns audio. */ +/** Owns queue commands, transport coordination and server synchronization. + * Cache remains the authoritative queue and owns local durability; AudioTransport owns audio. */ export class Playback { #selection: CacheSelection; #covers: Covers; #tracks: TrackEngine; - #player?: ReturnType; + #player?: AudioTransport; #isAvailable: (id: string) => boolean; #cleanup?: () => void; #selectedTrackId?: string; @@ -136,7 +135,7 @@ export class Playback { void this.next(); } - attach(player: ReturnType) { + attach(player: AudioTransport) { if (this.#destroyed) return () => {}; this.#cleanup?.(); this.#player = player; diff --git a/src/router.svelte b/src/router.svelte index a5fabd0..eacac8b 100644 --- a/src/router.svelte +++ b/src/router.svelte @@ -1,5 +1,27 @@ - 0} - onnext={() => props.playback.next()} - onprevious={() => props.playback.previous()} - onposition={(position) => props.playback.setPosition(position)} - onended={() => props.playback.ended()} - onstatechange={(state) => props.playback.updatePlayerState(state)} -/> +{#if audio} + 0} + onnext={() => props.playback.next()} + onprevious={() => props.playback.previous()} + /> +{/if} { - void playback.next(); - }, - onprevious: () => { - void playback.previous(); - }, - onposition: (position) => playback.setPosition(position), - onended: () => playback.ended(), - onstatechange: (state) => playback.updatePlayerState(state), - }, + const component = new AudioTransport({ + onposition: (position) => playback.setPosition(position), + onended: () => playback.ended(), + onstatechange: (state) => playback.updatePlayerState(state), }); flushSync(); playback.attach(component); flushSync(); cleanups.push(async () => { await playback.destroy(); - await unmount(component); + component.dispose(); tracks.destroy(); covers.destroy(); }); @@ -130,7 +119,7 @@ describe("playback queue synchronization", () => { it("publishes a complete normalized queue before unloading the previous selection", async () => { const { playback, selection, component } = await setup(); const seen: unknown[] = []; - const unload = component.unload; + const unload = component.unload.bind(component); vi.spyOn(component, "unload").mockImplementation(() => { seen.push(selection.cache!.queue); unload(); @@ -373,7 +362,7 @@ describe("playback queue synchronization", () => { await seed(); const { playback, cache, component } = await setup(); playback.setConnection(client()); - const unload = component.unload; + const unload = component.unload.bind(component); const reconcile = vi.spyOn(component, "unload").mockImplementation(() => { expect(cache.queue.tracks).toEqual(["remote"]); expect(playback.track?.id).toBe("remote"); diff --git a/tests/playback.test.ts b/tests/playback.test.ts index 2433c49..0b299ec 100644 --- a/tests/playback.test.ts +++ b/tests/playback.test.ts @@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { Playback } from "../src/playback.svelte"; import { flushSync, mount as mountComponent, unmount } from "svelte"; import Player from "../src/audio-player.svelte"; +import { AudioTransport } from "../src/audio-transport.svelte"; import { SvelteMap } from "svelte/reactivity"; import { observePlayback } from "./playback-reactivity.test.svelte"; import { Cache } from "../src/cache.svelte"; @@ -112,15 +113,21 @@ function setup(mount = true, isAvailable: (id: string) => boolean = () => true) covers: coverEngine, }); player.setQueue({ tracks: ["a", "b"], index: 0, position: 0 }); - let mountedPlayer: ReturnType; + let mountedPlayer: AudioTransport; const getPlayer = () => mountedPlayer; const queuePosition = () => selection.cache?.queue.position ?? 0; let detachMounted: (() => void) | undefined; const mountPlayer = () => { detachMounted?.(); + const transport = new AudioTransport({ + onposition: (position) => player.setPosition(position), + onended: () => player.ended(), + onstatechange: (state) => player.updatePlayerState(state), + }); const component = mountComponent(Player, { target: document.createElement("div"), props: { + transport, get hasNext() { const queue = selection.cache?.queue; return !!queue && queue.index >= 0 && queue.index < queue.tracks.length - 1; @@ -135,20 +142,18 @@ function setup(mount = true, isAvailable: (id: string) => boolean = () => true) onprevious: () => { void player.previous(); }, - onposition: (position) => player.setPosition(position), - onended: () => player.ended(), - onstatechange: (state) => player.updatePlayerState(state), }, }); - mountedPlayer = component; + mountedPlayer = transport; flushSync(); - const detachEngine = player.attach(component); + const detachEngine = player.attach(transport); flushSync(); let disposed = false; const detach = () => { if (disposed) return; disposed = true; detachEngine(); + transport.dispose(); void unmount(component); }; detachMounted = detach; @@ -248,7 +253,7 @@ describe("playback", () => { }; const publish = vi.spyOn(selection.cache!, "setQueue"); const component = getPlayer(); - const unload = component.unload; + const unload = component.unload.bind(component); const stop = vi.spyOn(component, "unload").mockImplementation(() => { expect(selection.cache!.queue).toEqual(expected); unload(); @@ -371,6 +376,7 @@ describe("playback", () => { expect(selection.cache!.queue.position).toBe(0); expect(getPlayer().playing).toBe(false); expect(audio.src).toBe(""); + flushSync(); expect(session.metadata).toBeNull(); }); @@ -910,6 +916,7 @@ describe("playback", () => { audio.dispatchEvent(new Event("loadedmetadata")); audio.currentTime = 32; audio.dispatchEvent(new Event("timeupdate")); + flushSync(); expect(selection.cache!.queue.position).toBe(32); expect(queuePosition()).toBe(32); expect(getPlayer().duration).toBe(120); @@ -1286,6 +1293,7 @@ describe("playback", () => { player.setQueue({ tracks: [], position: 0 }); expect(audio.src).toBe(""); expect(getPlayer().status).toBe("idle"); + flushSync(); expect(session.metadata).toBeNull(); }); }); diff --git a/tests/router-test-helpers.ts b/tests/router-test-helpers.ts index c58816b..91ac2ec 100644 --- a/tests/router-test-helpers.ts +++ b/tests/router-test-helpers.ts @@ -37,6 +37,14 @@ export function installNavigation( vi.stubGlobal("URLPattern", TestURLPattern); window.history.replaceState(null, "", `/?${path}`); const navigation = Object.assign(new EventTarget(), { + currentEntry: { url: window.location.href }, + commit(href: string, updateLocation = true) { + const url = new URL(href, window.location.href).href; + navigation.currentEntry = { url }; + navigation.dispatchEvent(new Event("currententrychange")); + if (updateLocation) window.history.replaceState(null, "", url); + }, + // A navigation attempt is not a commit; tests explicitly choose when to commit. navigate: vi.fn((href: string, options: { history: string }) => { onNavigate(href.slice(1), options.history); return { finished: Promise.resolve() }; diff --git a/tests/router.test.ts b/tests/router.test.ts index fc54da8..75ee51a 100644 --- a/tests/router.test.ts +++ b/tests/router.test.ts @@ -64,8 +64,18 @@ describe("router", () => { it.each([ ["/library", "library:{}"], + ["/player", "player:{}"], + ["/player=", "player:{}"], + ["/player=nonempty", "library:{}"], + ["/player==", "library:{}"], + ["q=one&/player", "library:{}"], + ["&/player", "library:{}"], + ["", "library:{}"], ["/library/artist/artist%201", 'artist:{"artistId":"artist 1"}'], ["/library/artist/a%2Fb%3Fc%23d%26e%25", 'artist:{"artistId":"a/b?c#d&e%"}'], + ["/library/artist/a%2Fb%3Fc%23d%26e%25&ignored=x", 'artist:{"artistId":"a/b?c#d&e%"}'], + ["/library/artist/a+b%2Bc%252F%26%3D=&ignored=x", 'artist:{"artistId":"a+b+c%2F&="}'], + ["/library/album/a+b%2Bc%252F%26%3D", 'album:{"albumId":"a+b+c%2F&="}'], ["/library/album/album-1", 'album:{"albumId":"album-1"}'], ["/library/album/a%2Fb%3Fc%23d%26e%25", 'album:{"albumId":"a/b?c#d&e%"}'], ["/unknown", "library:{}"], @@ -112,6 +122,30 @@ describe("router", () => { }, ); + it("updates same-route search with native scrolling and preserved focus", async () => { + const { navigation } = setup("/search=&unknown=old&type=artist&q=one"); + const start = vi.fn(); + document.startViewTransition = start; + const intercept = vi.fn((options: { handler: () => Promise }) => options.handler()); + navigation.dispatchEvent( + Object.assign(navigationEvent(), { + navigationType: "push", + canIntercept: true, + destination: { + url: new URL( + "?/search=&unknown=first&type=track&type=album&q=two&q=three&unknown=last#anchor", + window.location.href, + ).href, + }, + intercept, + }), + ); + await intercept.mock.results[0].value; + expect(intercept.mock.calls[0][0]).toMatchObject({ focusReset: "manual" }); + expect(intercept.mock.calls[0][0]).not.toHaveProperty("scroll"); + expect(start).not.toHaveBeenCalled(); + }); + it("does not navigate to the current URL", () => { const navigation = installNavigation("/library"); navigate("/library"); diff --git a/tests/search-filters.test.ts b/tests/search-filters.test.ts new file mode 100644 index 0000000..85b2d8a --- /dev/null +++ b/tests/search-filters.test.ts @@ -0,0 +1,178 @@ +// @vitest-environment happy-dom +import { flushSync, mount, unmount } from "svelte"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type Search from "../src/_search.svelte"; +import Harness from "./search-test-app.svelte"; +import type { ComponentProps } from "svelte"; + +afterEach(() => vi.unstubAllGlobals()); + +function fixture(count = 120) { + const artists = Array.from({ length: count }, (_, i) => ({ + id: `a${i}`, + name: `Fixture artist ${i}`, + })); + const albums = artists.map((a, i) => ({ + id: `b${i}`, + title: `Fixture album ${i}`, + artistIds: [a.id], + genres: [], + })); + const tracks = albums.map((a, i) => ({ + id: `t${i}`, + title: `Fixture track ${i}`, + albumId: a.id, + artistIds: a.artistIds, + genres: [], + })); + return { + cache: { + savedAt: 1, + queue: { tracks: [], index: 0 }, + artists: new Map(artists.map((a) => [a.id, a])), + albums: new Map(albums.map((a) => [a.id, a])), + tracks: new Map(tracks.map((a) => [a.id, a])), + artistAlbums: new Map(artists.map((a, i) => [a.id, [albums[i]]])), + albumTracks: new Map(albums.map((a, i) => [a.id, [tracks[i]]])), + }, + session: { localReady: true, offlineMode: false }, + covers: {}, + trackEngine: { getStatus: () => "downloaded" }, + playback: { toggleTrack: vi.fn(), replaceQueueAndPlay: vi.fn(), enqueue: vi.fn() }, + } as unknown as ComponentProps; +} + +describe("independent search filters", () => { + it("appends batches, retains rows across hash changes and resets on new criteria", async () => { + let callback: IntersectionObserverCallback; + vi.stubGlobal( + "IntersectionObserver", + class { + constructor(cb: IntersectionObserverCallback) { + callback = cb; + } + observe() {} + unobserve() {} + disconnect() {} + }, + ); + const target = document.createElement("main"); + document.body.append(target); + const app = mount(Harness, { target, props: { props: fixture(120) } }); + flushSync(); + try { + target.querySelectorAll("[aria-pressed]")[2].click(); + flushSync(); + const first = target.querySelector(".track-row"); + expect(target.querySelectorAll(".track-row")).toHaveLength(48); + for (const size of [96, 120]) { + const sentinel = target.querySelector(".library-sentinel")!; + callback!( + [{ target: sentinel, isIntersecting: true } as IntersectionObserverEntry], + {} as IntersectionObserver, + ); + flushSync(); + expect(target.querySelectorAll(".track-row")).toHaveLength(size); + expect(target.querySelector(".track-row")).toBe(first); + } + expect(target.querySelector(".library-sentinel")).toBeNull(); + expect(target.textContent).toContain("119"); + window.navigation.navigate("?/search&type=track#anchor", { history: "push" }); + flushSync(); + expect(target.querySelectorAll(".track-row")).toHaveLength(120); + const input = target.querySelector("input")!; + input.value = "Fixture"; + input.dispatchEvent(new Event("input", { bubbles: true })); + flushSync(); + expect(target.querySelectorAll(".track-row")).toHaveLength(48); + } finally { + await unmount(app); + target.remove(); + } + }); + it("filters offline browse eligibility before counting and retains album playback context", async () => { + const props = fixture(3); + const offlineProps = { + ...props, + session: { localReady: true, offlineMode: true }, + trackEngine: { getStatus: (id: string) => (id === "t2" ? "downloaded" : "idle") }, + } as unknown as ComponentProps; + const target = document.createElement("main"); + document.body.append(target); + const app = mount(Harness, { target, props: { props: offlineProps } }); + flushSync(); + try { + const trackChip = target.querySelectorAll("[aria-pressed]")[2]; + trackChip.click(); + flushSync(); + expect(target.querySelectorAll(".track-row")).toHaveLength(1); + expect(target.querySelector('section[aria-label="Tracks"] header')?.textContent).toContain( + "1", + ); + const play = target.querySelector(".track-row button.link-target")!; + expect(play.getAttribute("aria-label")).toBe("Play Fixture track 2"); + play.click(); + expect(props.playback.toggleTrack).toHaveBeenCalledWith("t2", ["t2"]); + const input = target.querySelector("input")!; + input.value = "Fixture track 0"; + input.dispatchEvent(new Event("input", { bubbles: true })); + flushSync(); + expect(target.textContent).toContain("No matches found."); + expect(target.querySelectorAll("[aria-pressed]")).toHaveLength(3); + } finally { + await unmount(app); + target.remove(); + } + }); + it.each(Array.from({ length: 8 }, (_, mask) => mask))( + "supports combination %s, previews and single-type batches", + async (mask) => { + const props = fixture(); + const target = document.createElement("main"); + document.body.append(target); + const app = mount(Harness, { target, props: { props } }); + flushSync(); + const chips = [...target.querySelectorAll("[aria-pressed]")]; + try { + chips.forEach((chip, i) => { + if (mask & (1 << i)) { + chip.click(); + flushSync(); + } + }); + flushSync(); + expect(chips.map((chip) => chip.getAttribute("aria-pressed"))).toEqual( + chips.map((_, i) => String(!!(mask & (1 << i)))), + ); + const selected = chips.filter((_, i) => mask & (1 << i)).length; + if (selected === 1) { + expect(target.querySelectorAll(".track-row")).toHaveLength(48); + expect(target.querySelector(".library-sentinel")).not.toBeNull(); + expect(target.querySelector("section[aria-label] header")?.textContent).toContain("120"); + expect(target.textContent).not.toContain("Show more"); + } else expect(target.textContent).toContain("Type to find music"); + const input = target.querySelector("input")!; + input.value = "Fixture"; + input.dispatchEvent(new Event("input", { bubbles: true })); + flushSync(); + expect(target.querySelectorAll("section[aria-label]").length).toBe(selected || 3); + expect(target.querySelectorAll(".library-sentinel").length).toBe(selected === 1 ? 1 : 0); + if (selected === 1) expect(target.querySelectorAll(".track-row")).toHaveLength(48); + if (selected !== 1) + expect(target.querySelectorAll(".track-row").length).toBe((selected || 3) * 3); + chips.forEach((chip) => { + if (chip.getAttribute("aria-pressed") === "true") { + chip.click(); + flushSync(); + } + }); + flushSync(); + expect(chips.every((chip) => chip.getAttribute("aria-pressed") === "false")).toBe(true); + expect(target.querySelectorAll(".track-row")).toHaveLength(9); + } finally { + await unmount(app); + target.remove(); + } + }, + ); +}); diff --git a/tests/search-page.test.ts b/tests/search-page.test.ts index 41b469d..3f79f4f 100644 --- a/tests/search-page.test.ts +++ b/tests/search-page.test.ts @@ -1,12 +1,14 @@ // @vitest-environment happy-dom import { flushSync, mount, unmount } from "svelte"; import fuzzysort from "fuzzysort"; -import { expect, it, vi } from "vitest"; +import { afterEach, expect, it, vi } from "vitest"; + +afterEach(() => vi.unstubAllGlobals()); import Harness from "./search-test-app.svelte"; import type Search from "../src/_search.svelte"; import type { ComponentProps } from "svelte"; -it("focuses the input, expands results, retains route state, and uses album playback", async () => { +it("focuses the input, expands previews, retains URL criteria, and uses album playback", async () => { const tracks = Array.from({ length: 12 }, (_, i) => ({ id: String(i), title: "Song", @@ -36,7 +38,7 @@ it("focuses the input, expands results, retains route state, and uses album play ensureCover: () => cover, }, playback, - } as unknown as Omit, "state">; + } as unknown as ComponentProps; const target = document.createElement("div"); document.body.append(target); const app = mount(Harness, { target, props: { props } }); @@ -151,7 +153,7 @@ it("focuses the input, expands results, retains route state, and uses album play flushSync(); input = target.querySelector("input")!; expect(input.value).toBe("Song"); - expect(target.querySelectorAll(".track-row button.link-target")).toHaveLength(12); + expect(target.querySelectorAll(".track-row button.link-target")).toHaveLength(3); // Native search cancellation emits an input event with an empty value. input.value = ""; input.dispatchEvent(new Event("input", { bubbles: true })); @@ -199,10 +201,12 @@ it.each([ trackEngine: { getStatus: () => "idle" }, covers: {}, playback: {}, - } as unknown as Omit, "state">; + } as unknown as ComponentProps; const app = mount(Harness, { target, props: { props } }); flushSync(); try { + expect(target.querySelectorAll('[aria-label="Result types"] button')).toHaveLength(3); + if (!localReady) expect(target.textContent).toContain("Loading your library…"); expect(target.querySelector("[aria-busy]")?.getAttribute("aria-busy")).toBe( String(!localReady), ); diff --git a/tests/search-params-test-reader.svelte.ts b/tests/search-params-test-reader.svelte.ts new file mode 100644 index 0000000..ade6247 --- /dev/null +++ b/tests/search-params-test-reader.svelte.ts @@ -0,0 +1,8 @@ +import { getSearchParameters } from "../src/router.svelte"; + +export function observeSearchParameters(read: (parameters: URLSearchParams) => void) { + return $effect.root(() => { + const parameters = $derived(getSearchParameters()); + $effect(() => read(parameters)); + }); +} diff --git a/tests/search-params.test.ts b/tests/search-params.test.ts new file mode 100644 index 0000000..b55305b --- /dev/null +++ b/tests/search-params.test.ts @@ -0,0 +1,83 @@ +// @vitest-environment happy-dom +import { flushSync, tick } from "svelte"; +import { afterEach, expect, it, vi } from "vitest"; +import { getSearchParameters } from "../src/router.svelte"; +import { observeSearchParameters } from "./search-params-test-reader.svelte"; +import { installNavigation, navigationEvent } from "./router-test-helpers"; + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +it("reads the complete initial parameters without mounting Router", () => { + installNavigation("/search=&unknown=first&type=album&type=track&q=one&q=two&unknown=last"); + expect([...getSearchParameters()]).toEqual([ + ["/search", ""], + ["unknown", "first"], + ["type", "album"], + ["type", "track"], + ["q", "one"], + ["q", "two"], + ["unknown", "last"], + ]); +}); + +it("reads the committed entry even while location still names the previous entry", () => { + const navigation = installNavigation("/search&q=old"); + navigation.commit("?/search&q=committed", false); + expect(new URL(window.location.href).searchParams.get("q")).toBe("old"); + expect(getSearchParameters().get("q")).toBe("committed"); +}); + +it("falls back to location when no current entry URL is available", () => { + installNavigation("/search&q=fallback"); + vi.stubGlobal("navigation", { currentEntry: undefined }); + expect(getSearchParameters().get("q")).toBe("fallback"); +}); + +it("reacts only to commits, preserves hash identity and reads fresh state after disposal", async () => { + const navigation = installNavigation("/search&q=initial"); + const read = vi.fn(); + let stop = observeSearchParameters(read); + try { + flushSync(); + expect(read.mock.lastCall![0].get("q")).toBe("initial"); + navigation.navigate("?/search&q=attempt", { history: "push" }); + const controller = new AbortController(); + controller.abort(); + navigation.dispatchEvent( + Object.assign(navigationEvent(), { + signal: controller.signal, + destination: { url: new URL("?/search&q=canceled", window.location.href).href }, + }), + ); + flushSync(); + expect(read.mock.lastCall![0].get("q")).toBe("initial"); + navigation.commit("?/search&q=committed", false); + flushSync(); + expect(read.mock.lastCall![0].get("q")).toBe("committed"); + const parameters = getSearchParameters(); + navigation.commit("?/search&q=committed#anchor", false); + flushSync(); + expect(getSearchParameters()).toBe(parameters); + navigation.commit("?unrouted=one&unrouted=two", false); + flushSync(); + expect([...read.mock.lastCall![0]]).toEqual([ + ["unrouted", "one"], + ["unrouted", "two"], + ]); + stop(); + await tick(); + read.mockClear(); + navigation.commit("?/search&q=while-unsubscribed"); + flushSync(); + expect(read).not.toHaveBeenCalled(); + stop = observeSearchParameters(read); + flushSync(); + expect(read.mock.lastCall![0].get("q")).toBe("while-unsubscribed"); + } finally { + stop(); + await tick(); + } +}); diff --git a/tests/search-test-app.svelte b/tests/search-test-app.svelte index 57c5526..29aa41e 100644 --- a/tests/search-test-app.svelte +++ b/tests/search-test-app.svelte @@ -1,10 +1,14 @@ -{#if visible}{/if} +{#if visible}{/if} diff --git a/tests/search.test.ts b/tests/search.test.ts index da00f24..af9401b 100644 --- a/tests/search.test.ts +++ b/tests/search.test.ts @@ -1,7 +1,55 @@ import { describe, expect, it } from "vitest"; -import { createSearchIndex, searchLibrary } from "../src/_search.svelte"; +import { + createSearchIndex, + searchLibrary, + parseSearch, + searchHref, + searchTypes, +} from "../src/_search.svelte"; import type { Album, Artist, Track } from "../src/schema"; +describe("shareable search URLs", () => { + it.each(Array.from({ length: 8 }, (_, mask) => mask))("round trips combination %s", (mask) => { + const types = searchTypes.filter((_, i) => mask & (1 << i)); + for (const query of ["", " ", "Beyoncé 東京 + & % / ? #"]) { + const url = new URL(searchHref(query, types), "https://example.test/demo/"); + expect(url.search.startsWith("?/search")).toBe(true); + expect(url.searchParams.get("/search")).toBe(""); + expect(parseSearch(url.searchParams)).toEqual({ query, types }); + expect(url.pathname).toBe("/demo/"); + expect(url.hash).toBe(""); + } + }); + + it("reads only q/types from complete parameters without mutating them", () => { + const parameters = new URLSearchParams( + "/search&type=track&unknown=keep&type=no&type=artist&type=track&q=first&q=second", + ); + const entries = [...parameters]; + const criteria = parseSearch(parameters); + expect(criteria).toEqual({ query: "first", types: ["artist", "track"] }); + expect([...parameters]).toEqual(entries); + expect(searchHref(criteria.query, criteria.types)).toBe( + "?/search&type=artist&type=track&q=first", + ); + expect(searchHref("lemonade", ["album", "album"])).toBe("?/search&type=album&q=lemonade"); + expect(parseSearch(new URLSearchParams("/search&type=unknown"))).toEqual({ + query: "", + types: [], + }); + expect(parseSearch(new URLSearchParams("/search&q=&q=second"))).toEqual({ + query: "", + types: [], + }); + expect(searchHref()).toBe("?/search"); + }); + + it("does not read search criteria from an anchor", () => { + const url = new URL("https://example.test/?/search#q=ignored&type=track"); + expect(parseSearch(url.searchParams)).toEqual({ query: "", types: [] }); + }); +}); + function fixture(count = 12) { const artists = new Map([["a", { id: "a", name: "Beyoncé" }]]); const albums = new Map([ @@ -42,6 +90,17 @@ describe("local library search", () => { expect(search(query).every((group) => group.total === 0)).toBe(true); } }); + it("enumerates complete single-type browse results in cache order, including offline eligibility", () => { + const { artists, albums, tracks } = fixture(1500); + const reverse = new Map([...tracks].reverse()); + const index = createSearchIndex(artists, albums, reverse); + const result = searchLibrary(index, " ", true).groups[2]; + expect(result.total).toBe(1500); + expect(result.records.map((record) => record.id)).toEqual([...reverse.keys()]); + expect(searchLibrary(index, "formation", true).groups[2].total).toBe(1500); + const offline = createSearchIndex(artists, albums, reverse, (id) => id === "1499"); + expect(searchLibrary(offline, "", true).groups.map((group) => group.total)).toEqual([1, 1, 1]); + }); it("ranks all matches independently of pagination and keeps ties deterministic", () => { expect(search("formation")[2].records.map((r) => r.id)).toEqual([...tracks.keys()]); const reverse = createSearchIndex(artists, albums, new Map([...tracks].reverse()));