From 95f866ef7a10fcab1137e8263e56bfd55c1aff25 Mon Sep 17 00:00:00 2001 From: Bogdan Chadkin Date: Wed, 11 Nov 2026 16:15:47 +0100 Subject: [PATCH 1/8] Add search type filters and virtualized result lists --- src/_search.svelte | 313 +++++++++++++++++++++++++--------- src/app.svelte | 17 +- src/router.svelte | 37 +++- src/search-url.ts | 30 ++++ src/ui/virtual-list.svelte | 182 ++++++++++++++++++++ tests/browser/search.test.cjs | 292 ++++++++++++++++++++++++++++++- tests/router.test.ts | 47 +++++ tests/search-filters.test.ts | 129 ++++++++++++++ tests/search-page.test.ts | 2 + tests/search-url.test.ts | 34 ++++ tests/search.test.ts | 11 ++ 11 files changed, 1001 insertions(+), 93 deletions(-) create mode 100644 src/search-url.ts create mode 100644 src/ui/virtual-list.svelte create mode 100644 tests/search-filters.test.ts create mode 100644 tests/search-url.test.ts diff --git a/src/_search.svelte b/src/_search.svelte index 63ad754..25946be 100644 --- a/src/_search.svelte +++ b/src/_search.svelte @@ -17,7 +17,11 @@ } export function createSearchState() { - return { query: "", limits: { Artists: 3, Albums: 3, Tracks: 3 } }; + return { + query: "", + types: [] as import("./search-url").SearchType[], + limits: { Artists: 3, Albums: 3, Tracks: 3 }, + }; } type SearchState = ReturnType; @@ -87,6 +91,7 @@ keys: ["title", "artist", "album"], }); return { + records, Artists: snapshot("Artists"), Albums: snapshot("Albums"), Tracks: snapshot("Tracks"), @@ -94,7 +99,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 +122,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 }; @@ -122,7 +131,11 @@ + +
    queueMicrotask(focusChanged)} +> + {#each visible as i (items[i].id)} + +
  • tab(event, i)} + > + {@render row(items[i])} +
  • + {/each} +
+ + diff --git a/tests/browser/search.test.cjs b/tests/browser/search.test.cjs index 4367ff8..937a455 100644 --- a/tests/browser/search.test.cjs +++ b/tests/browser/search.test.cjs @@ -3,6 +3,8 @@ const assert = require("node:assert/strict"); const { test } = require("node:test"); const { chromium } = require("playwright"); const base = process.env.PREVIEW_URL ?? "http://127.0.0.1:5173"; +const screenshots = process.env.SCREENSHOT_DIR; +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); test("Search responsive layout and native actions", async () => { const browser = await chromium.launch({ headless: true }); @@ -17,9 +19,19 @@ test("Search responsive layout and native actions", async () => { name: "Search fixture artist with a long name that wraps naturally", }; const album = { id: "album", name: "Search fixture album", artists: [artist], year: 2024 }; - const songs = Array.from({ length: 4 }, (_, i) => ({ + const directoryArtists = Array.from({ length: 1499 }, (_, i) => ({ + id: `directory-artist-${i}`, + name: `Directory artist ${i}`, + })); + const directoryAlbums = directoryArtists.map((a, i) => ({ + id: `directory-album-${i}`, + name: `Directory album ${i}`, + artists: [a], + year: 2024, + })); + const songs = Array.from({ length: 1500 }, (_, i) => ({ id: `track-${i}`, - title: `Search fixture track ${i}`, + title: `Search fixture track ${i}${i % 17 === 0 ? " — a very long title with multiple wrapped lines and Unicode Beyoncé 東京, to measure rather than truncate" : ""}`, albumId: album.id, artists: [artist], duration: 123, @@ -37,8 +49,10 @@ test("Search responsive layout and native actions", async () => { else if (method === "search3") fields = { searchResult3: { - artist: Number(url.searchParams.get("artistOffset")) === 0 ? [artist] : [], - album: Number(url.searchParams.get("albumOffset")) === 0 ? [album] : [], + artist: + Number(url.searchParams.get("artistOffset")) === 0 ? [artist, ...directoryArtists] : [], + album: + Number(url.searchParams.get("albumOffset")) === 0 ? [album, ...directoryAlbums] : [], song: Number(url.searchParams.get("songOffset")) === 0 ? songs : [], }, }; @@ -53,7 +67,7 @@ test("Search responsive layout and native actions", async () => { await page.getByLabel("Username", { exact: true }).fill("listener"); await page.getByLabel("Password", { exact: true }).fill("fictional-password"); await page.getByRole("button", { name: "Connect", exact: true }).click(); - await page.locator(".tile").waitFor(); + await page.locator(".tile").first().waitFor(); await page.locator('a[href="?/search"]').filter({ visible: true }).click(); const input = page.getByRole("searchbox", { name: "Search library" }); await input.waitFor(); @@ -64,7 +78,7 @@ test("Search responsive layout and native actions", async () => { await tracks.locator(".track-row").first().waitFor(); assert.equal(await artists.locator(".artwork-placeholder").isVisible(), true); const options = tracks.getByRole("button", { - name: `Open menu for ${songs[0].title}`, + name: `Open menu for ${songs[1].title}`, exact: true, }); for (const width of [320, 768, 1280]) { @@ -72,7 +86,7 @@ test("Search responsive layout and native actions", async () => { await options.filter({ visible: true }).click(); const panel = page.locator(width > 800 ? "#search-menu-popover" : "#search-menu"); await panel.waitFor({ state: "visible" }); - assert.equal(await panel.getByRole("heading").textContent(), songs[0].title); + assert.equal(await panel.getByRole("heading").textContent(), songs[1].title); await page.keyboard.press("Escape"); assert.equal( await options.filter({ visible: true }).evaluate((node) => node === document.activeElement), @@ -86,7 +100,7 @@ test("Search responsive layout and native actions", async () => { ); } // Long press uses the sheet even on desktop, with focus restored on dismissal. - const target = tracks.getByRole("button", { name: `Play ${songs[1].title}`, exact: true }); + const target = tracks.getByRole("button", { name: `Play ${songs[2].title}`, exact: true }); await target.scrollIntoViewIfNeeded(); const box = await target.boundingBox(); await page.mouse.move(box.x + 8, box.y + 8); @@ -95,7 +109,7 @@ test("Search responsive layout and native actions", async () => { await sheet.waitFor({ state: "visible" }); await page.mouse.up(); assert.equal(await sheet.evaluate((node) => node.matches(":modal")), true); - assert.equal(await sheet.getByRole("heading").textContent(), songs[1].title); + assert.equal(await sheet.getByRole("heading").textContent(), songs[2].title); await sheet.getByRole("button", { name: "Close menu" }).click(); assert.equal(await target.evaluate((node) => node === document.activeElement), true); await page.setViewportSize({ width: 393, height: 852 }); @@ -124,6 +138,266 @@ test("Search responsive layout and native actions", async () => { ), true, ); + await page.evaluate(() => { + document.documentElement.style.fontSize = ""; + }); + await page.setViewportSize({ width: 1280, height: 900 }); + await input.fill("Search fixture"); + const chips = ["Artist", "Album", "Track"].map((name) => + page.getByRole("button", { name, exact: true }), + ); + for (let mask = 0; mask < 8; mask++) { + for (let i = 0; i < chips.length; i++) { + if (((await chips[i].getAttribute("aria-pressed")) === "true") !== !!(mask & (1 << i))) + await chips[i].click(); + } + const count = [0, 1, 2].filter((i) => mask & (1 << i)).length; + assert.equal( + await page.locator('section[aria-label="Artists"]').count(), + !mask || mask & 1 ? 1 : 0, + ); + assert.equal( + await page.locator('section[aria-label="Albums"]').count(), + !mask || mask & 2 ? 1 : 0, + ); + assert.equal( + await page.locator('section[aria-label="Tracks"]').count(), + !mask || mask & 4 ? 1 : 0, + ); + assert.equal(await page.locator(".virtual-list").count(), count === 1 ? 1 : 0); + } + await chips[0].click(); + await chips[1].click(); // Track only. + await chips[2].focus(); + await page.keyboard.press("Space"); + assert.equal(await chips[2].getAttribute("aria-pressed"), "false"); + assert.equal(await chips[2].evaluate((node) => node === document.activeElement), true); + await page.keyboard.press("Enter"); + assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); + await input.fill(""); + await page.locator('.virtual-list li[aria-setsize="1500"]').first().waitFor(); + assert.equal(await tracks.locator(".metadata").first().textContent(), "1500"); + const rowCount = async () => tracks.locator(".track-row").count(); + assert.ok((await rowCount()) < 40); + assert.equal(await page.getByRole("button", { name: "Show more tracks" }).count(), 0); + const browseURL = page.url(); + assert.ok(browseURL.includes("type=track")); + await page.reload(); + await page.locator('.virtual-list li[aria-setsize="1500"]').first().waitFor(); + assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); + // Sequential Tab crosses the virtual window, not straight out of the list. + const lastMounted = page.locator(".virtual-list li").last(); + const lastIndex = Number(await lastMounted.getAttribute("data-index")); + await lastMounted + .getByRole("button", { name: /^Open menu/ }) + .filter({ visible: true }) + .focus(); + await page.keyboard.press("Tab"); + assert.equal( + await page.evaluate(() => Number(document.activeElement.closest("li").dataset.index)), + lastIndex + 1, + ); + await page.keyboard.press("Shift+Tab"); + assert.equal( + await page.evaluate(() => Number(document.activeElement.closest("li").dataset.index)), + lastIndex, + ); + // Open menus keep their invoker mounted even when it leaves the window. + await page.evaluate(() => window.scrollTo(0, 0)); + await wait(150); + const firstOptions = tracks + .getByRole("button", { name: `Open menu for ${songs[0].title}`, exact: true }) + .filter({ visible: true }); + await firstOptions.click(); + await page.locator("#search-menu-popover").waitFor({ state: "visible" }); + await input.click(); + await page.locator("#search-menu-popover").waitFor({ state: "hidden" }); + await wait(100); + assert.equal(await input.evaluate((node) => node === document.activeElement), true); + await firstOptions.click(); + await page.locator("#search-menu-popover").waitFor({ state: "visible" }); + if (screenshots) await page.screenshot({ path: `${screenshots}/search-desktop-menu.png` }); + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + await wait(200); + assert.equal(await firstOptions.count(), 1); + await page.keyboard.press("Escape"); + await wait(100); + assert.equal(await firstOptions.evaluate((node) => node === document.activeElement), true); + assert.ok(await firstOptions.evaluate((node) => node.getBoundingClientRect().bottom > 0)); + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + await wait(200); + await tracks.getByRole("button", { name: `Play ${songs[1499].title}`, exact: true }).waitFor(); + assert.ok((await rowCount()) < 40); + await page.evaluate(() => window.scrollTo(0, 0)); + await wait(200); + assert.ok((await rowCount()) < 40); + // Wrapped measurements do not overlap and resize remains bounded. + for (const width of [1280, 320]) { + await page.setViewportSize({ width, height: 900 }); + await wait(200); + const geometry = await page.locator(".virtual-list li").evaluateAll((nodes) => + nodes.map((node) => { + const r = node.getBoundingClientRect(); + return { top: r.top, bottom: r.bottom }; + }), + ); + for (let i = 1; i < geometry.length; i++) + assert.ok(geometry[i].top >= geometry[i - 1].bottom - 1); + assert.equal( + await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), + true, + ); + await chips[2].focus(); + if (screenshots) + await page.screenshot({ + path: `${screenshots}/search-${width === 320 ? "narrow" : "desktop"}.png`, + }); + if (width === 320) { + await firstOptions.click(); + await sheet.waitFor({ state: "visible" }); + if (screenshots) await page.screenshot({ path: `${screenshots}/search-narrow-menu.png` }); + await page.keyboard.press("Escape"); + assert.equal(await firstOptions.evaluate((node) => node === document.activeElement), true); + await page.evaluate(() => { + document.documentElement.style.fontSize = "200%"; + }); + await wait(200); + assert.equal( + await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), + true, + ); + assert.ok((await rowCount()) < 40); + await page.evaluate(() => { + document.documentElement.style.fontSize = ""; + }); + } + } + // Typing replaces; chips push; Back/Forward and direct URLs remain authoritative. + const special = "Beyoncé 東京 + & % / ? #"; + const before = await page.evaluate(() => navigation.entries().length); + await input.fill(special); + await page.waitForURL( + (url) => new URLSearchParams(url.search.split("&").slice(1).join("&")).get("q") === special, + ); + assert.equal(await page.evaluate(() => navigation.entries().length), before); + if (screenshots) await page.screenshot({ path: `${screenshots}/search-no-matches.png` }); + await chips[0].click(); + await page.goBack(); + assert.equal(await input.inputValue(), special); + assert.equal(await chips[0].getAttribute("aria-pressed"), "false"); + await page.goForward(); + assert.equal(await chips[0].getAttribute("aria-pressed"), "true"); + await page.goto(`${base}/?/search&type=track&q=Search+fixture#search-anchor`); + await tracks.locator(".track-row").first().waitFor(); + assert.equal(await input.inputValue(), "Search fixture"); + assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); + assert.equal(new URL(page.url()).hash, "#search-anchor"); + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + await wait(200); + assert.ok((await rowCount()) < 40); + // Single-type matches reach the actual final result too (score order is deterministic). + await input.fill("Search fixture track 1499"); + await tracks.getByRole("button", { name: `Play ${songs[1499].title}`, exact: true }).waitFor(); + assert.equal(await input.evaluate((node) => node === document.activeElement), true); + // Result navigation and Back restore URL criteria; a bare Search link resets them. + await chips[2].click(); + await chips[0].click(); + await input.fill("Search fixture"); + await artists.getByRole("link", { name: artist.name, exact: true }).click(); + await page.goBack(); + await input.waitFor(); + assert.equal(await input.inputValue(), "Search fixture"); + assert.equal(await chips[0].getAttribute("aria-pressed"), "true"); + await page.locator('a[href="?/search"]').filter({ visible: true }).click(); + assert.equal(await input.inputValue(), ""); + assert.equal(await chips[0].getAttribute("aria-pressed"), "false"); + for (const [i, group] of [ + [0, "Artists"], + [1, "Albums"], + ]) { + await chips[i].click(); + const region = page.getByRole("region", { name: group, exact: true }); + await region.locator('.virtual-list li[aria-setsize="1500"]').first().waitFor(); + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + await wait(200); + assert.equal( + await region.locator(".virtual-list li").last().getAttribute("aria-posinset"), + "1500", + ); + const lastLink = region.locator(".virtual-list li").last().getByRole("link"); + await lastLink.waitFor(); + assert.ok((await region.locator(".track-row").count()) < 40); + if (i === 1) { + const y = await page.evaluate(() => scrollY); + await lastLink.click(); + await page.goBack(); + await lastLink.waitFor(); + assert.ok((await page.evaluate(() => scrollY)) > y * 0.8); + assert.equal(await chips[i].getAttribute("aria-pressed"), "true"); + } + await input.fill("Directory"); + await region.locator('.virtual-list li[aria-setsize="1499"]').first().waitFor(); + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + await wait(200); + assert.ok((await region.locator(".track-row").count()) < 40); + assert.equal( + await region.locator(".virtual-list li").last().getAttribute("aria-posinset"), + "1499", + ); + await input.fill(""); + await chips[i].click(); + } + // Incoming same-route anchors must not inherit a deeply scrolled virtual window. + // Keep the anchor at the current viewport so clicking it cannot mask the bug + // by scrolling the page to the search controls before navigation. + await chips[2].click(); + await tracks.locator('.virtual-list li[aria-setsize="1500"]').first().waitFor(); + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight / 2)); + await wait(200); + const deepScroll = await page.evaluate(() => scrollY); + assert.ok(deepScroll > 10000); + await page.evaluate(() => { + const link = document.createElement("a"); + link.id = "incoming-search-link"; + link.href = "?/search&type=album&q=Directory"; + link.textContent = "Browse directory albums"; + Object.assign(link.style, { + position: "fixed", + bottom: "16px", + left: "16px", + zIndex: "9999", + }); + document.body.append(link); + }); + await page.getByRole("link", { name: "Browse directory albums", exact: true }).click(); + const firstAlbum = page.locator( + 'section[aria-label="Albums"] .virtual-list li[data-index="0"]', + ); + await firstAlbum.waitFor(); + await page.waitForFunction(() => { + const first = document.querySelector( + 'section[aria-label="Albums"] .virtual-list li[data-index="0"]', + ); + if (!first) return false; + const bounds = first.getBoundingClientRect(); + return scrollY < 200 && bounds.top >= 0 && bounds.top < innerHeight; + }); + assert.equal(await input.inputValue(), "Directory"); + assert.equal(await chips[1].getAttribute("aria-pressed"), "true"); + await page.goBack(); + await tracks.locator(".track-row").first().waitFor(); + assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); + assert.equal(await input.inputValue(), ""); + assert.ok((await page.evaluate(() => scrollY)) > deepScroll * 0.8); + await page.goForward(); + await firstAlbum.waitFor(); + assert.ok( + await firstAlbum.evaluate((node) => { + const bounds = node.getBoundingClientRect(); + return bounds.top >= 0 && bounds.top < innerHeight; + }), + ); + await page.locator("#incoming-search-link").evaluate((node) => node.remove()); assert.deepEqual(errors, []); } finally { await browser.close(); diff --git a/tests/router.test.ts b/tests/router.test.ts index fc54da8..c856e46 100644 --- a/tests/router.test.ts +++ b/tests/router.test.ts @@ -66,6 +66,7 @@ describe("router", () => { ["/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/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 +113,43 @@ describe("router", () => { }, ); + it.each([ + { navigationType: "push", local: false }, + { navigationType: "replace", local: false }, + { navigationType: "push", local: true }, + { navigationType: "replace", local: true }, + { navigationType: "traverse", local: false }, + { navigationType: "traverse", local: true }, + ])( + "updates same-route search $navigationType (local: $local) with appropriate scroll handling", + async ({ navigationType, local }) => { + const { navigation } = setup("/search&type=artist&q=one"); + expect(route.parameters.get("q")).toBe("one"); + const start = vi.fn(); + document.startViewTransition = start; + const intercept = vi.fn((options: { handler: () => Promise }) => options.handler()); + navigation.dispatchEvent( + Object.assign(navigationEvent(), { + navigationType, + info: local ? { preserveScroll: true } : undefined, + canIntercept: true, + destination: { + url: new URL("?/search&type=track&q=two#anchor", window.location.href).href, + }, + intercept, + }), + ); + await intercept.mock.results[0].value; + expect(route.parameters.get("q")).toBe("two"); + expect(route.parameters.getAll("type")).toEqual(["track"]); + expect(intercept.mock.calls[0][0]).toMatchObject({ focusReset: "manual" }); + if (local && navigationType !== "traverse") + expect(intercept.mock.calls[0][0]).toMatchObject({ scroll: "manual" }); + else 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"); @@ -148,6 +186,15 @@ describe("router", () => { expect(navigation.navigate).toHaveBeenLastCalledWith("?/player", { history: "replace" }); }); + it("marks local search updates without changing ordinary navigation options", () => { + const navigation = installNavigation("/search&type=artist"); + navigate("/search&type=album", "push", { preserveScroll: true }); + expect(navigation.navigate).toHaveBeenCalledWith("?/search&type=album", { + history: "push", + info: { preserveScroll: true }, + }); + }); + it.each(["/webapp/", "/webapp/?section"])("renders the fallback without rewriting %s", (url) => { const { navigation, target } = setup("/library", url); expect(window.location.href).toBe(new URL(url, window.location.origin).href); diff --git a/tests/search-filters.test.ts b/tests/search-filters.test.ts new file mode 100644 index 0000000..e6e6ba5 --- /dev/null +++ b/tests/search-filters.test.ts @@ -0,0 +1,129 @@ +// @vitest-environment happy-dom +import { flushSync, mount, unmount } from "svelte"; +import { describe, expect, it, vi } from "vitest"; +import Search, { createSearchState } from "../src/_search.svelte"; +import Harness from "./search-test-app.svelte"; +import type { ComponentProps } from "svelte"; + +function fixture() { + const artists = Array.from({ length: 1500 }, (_, 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() }, + state: createSearchState(), + } as unknown as ComponentProps; +} + +describe("independent search filters", () => { + it("filters offline browse eligibility before counting and retains album playback context", async () => { + const props = fixture(); + const offlineProps = { + ...props, + session: { localReady: true, offlineMode: true }, + trackEngine: { getStatus: (id: string) => (id === "t1499" ? "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("li[aria-setsize]")?.getAttribute("aria-setsize")).toBe("1"); + const play = target.querySelector(".track-row button.link-target")!; + expect(play.getAttribute("aria-label")).toBe("Play Fixture track 1499"); + play.click(); + expect(props.playback.toggleTrack).toHaveBeenCalledWith("t1499", ["t1499"]); + 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 full bounded browse", + 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.querySelector(".virtual-list")).not.toBeNull(); + expect(target.querySelectorAll(".track-row").length).toBeLessThan(30); + expect(target.querySelector("li[aria-setsize]")?.getAttribute("aria-setsize")).toBe( + "1500", + ); + 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(".virtual-list").length).toBe(selected === 1 ? 1 : 0); + 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..2826656 100644 --- a/tests/search-page.test.ts +++ b/tests/search-page.test.ts @@ -203,6 +203,8 @@ it.each([ 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-url.test.ts b/tests/search-url.test.ts new file mode 100644 index 0000000..8eef6ae --- /dev/null +++ b/tests/search-url.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; +import { parseSearch, searchHref, searchTypes, splitRoute } from "../src/search-url"; + +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/"); + const { path, parameters } = splitRoute(url.search); + expect(path).toBe("/search"); + expect(parseSearch(parameters)).toEqual({ query, types }); + expect(url.pathname).toBe("/demo/"); + expect(url.hash).toBe(""); + } + }); + it("ignores unknown types, deduplicates and canonicalizes, and uses the first q", () => { + const criteria = parseSearch( + new URLSearchParams("type=track&type=no&type=artist&type=track&q=first&q=second"), + ); + expect(criteria).toEqual({ query: "first", types: ["artist", "track"] }); + expect(searchHref(criteria.query, criteria.types)).toBe( + "?/search&type=artist&type=track&q=first", + ); + expect(parseSearch(new URLSearchParams("type=unknown"))).toEqual({ query: "", types: [] }); + expect(searchHref()).toBe("?/search"); + }); + it("splits literal delimiters before decoding route IDs and leaves hash separate", () => { + const url = new URL( + "https://example.test/?/library/artist/a%26b%2Fc%3Fd%23e%25&ignored=x#anchor", + ); + expect(splitRoute(url.search).path).toBe("/library/artist/a%26b%2Fc%3Fd%23e%25"); + expect(url.hash).toBe("#anchor"); + }); +}); diff --git a/tests/search.test.ts b/tests/search.test.ts index da00f24..d653631 100644 --- a/tests/search.test.ts +++ b/tests/search.test.ts @@ -42,6 +42,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())); From 61a0e520319c6e54883d543b93986d0ff0d377f9 Mon Sep 17 00:00:00 2001 From: Bogdan Chadkin Date: Wed, 11 Nov 2026 17:29:26 +0100 Subject: [PATCH 2/8] Simplify search lists and filter state --- src/_search.svelte | 334 +++++++++++------------------- src/app.svelte | 26 +-- src/router.svelte | 25 +-- src/ui/virtual-list.svelte | 182 ---------------- tests/browser/search.test.cjs | 377 +++++++++++----------------------- tests/router.test.ts | 27 +-- tests/search-filters.test.ts | 75 +++++-- tests/search-page.test.ts | 12 +- tests/search-test-app.svelte | 20 +- 9 files changed, 330 insertions(+), 748 deletions(-) delete mode 100644 src/ui/virtual-list.svelte diff --git a/src/_search.svelte b/src/_search.svelte index 25946be..d30906b 100644 --- a/src/_search.svelte +++ b/src/_search.svelte @@ -16,16 +16,6 @@ artworkId?: string; } - export function createSearchState() { - return { - query: "", - types: [] as import("./search-url").SearchType[], - limits: { Artists: 3, Albums: 3, Tracks: 3 }, - }; - } - - type SearchState = ReturnType; - function availableTrackIds( tracks: readonly Immutable[], isAvailable: (id: string) => boolean, @@ -131,11 +121,10 @@ - -
    queueMicrotask(focusChanged)} -> - {#each visible as i (items[i].id)} - -
  • tab(event, i)} - > - {@render row(items[i])} -
  • - {/each} -
- - diff --git a/tests/browser/search.test.cjs b/tests/browser/search.test.cjs index 937a455..884f35e 100644 --- a/tests/browser/search.test.cjs +++ b/tests/browser/search.test.cjs @@ -4,9 +4,8 @@ const { test } = require("node:test"); const { chromium } = require("playwright"); const base = process.env.PREVIEW_URL ?? "http://127.0.0.1:5173"; const screenshots = process.env.SCREENSHOT_DIR; -const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); -test("Search responsive layout and native actions", async () => { +test("Search filters, incremental lists, URLs and native actions", async () => { const browser = await chromium.launch({ headless: true }); const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, @@ -19,7 +18,7 @@ test("Search responsive layout and native actions", async () => { name: "Search fixture artist with a long name that wraps naturally", }; const album = { id: "album", name: "Search fixture album", artists: [artist], year: 2024 }; - const directoryArtists = Array.from({ length: 1499 }, (_, i) => ({ + const directoryArtists = Array.from({ length: 149 }, (_, i) => ({ id: `directory-artist-${i}`, name: `Directory artist ${i}`, })); @@ -29,9 +28,9 @@ test("Search responsive layout and native actions", async () => { artists: [a], year: 2024, })); - const songs = Array.from({ length: 1500 }, (_, i) => ({ + const songs = Array.from({ length: 150 }, (_, i) => ({ id: `track-${i}`, - title: `Search fixture track ${i}${i % 17 === 0 ? " — a very long title with multiple wrapped lines and Unicode Beyoncé 東京, to measure rather than truncate" : ""}`, + title: `Search fixture track ${i}${i === 0 ? " — a long title with naturally wrapped lines and Unicode Beyoncé 東京" : ""}`, albumId: album.id, artists: [artist], duration: 123, @@ -61,6 +60,22 @@ test("Search responsive layout and native actions", async () => { body: JSON.stringify({ "subsonic-response": { status: "ok", ...fields } }), }); }); + + async function loadAll(region, total) { + const first = await region.locator(".track-row").first().elementHandle(); + while ((await region.locator(".track-row").count()) < total) { + const count = await region.locator(".track-row").count(); + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + await region + .locator(".track-row") + .nth(Math.min(count + 47, total - 1)) + .waitFor(); + assert.equal(await first.evaluate((node) => node.isConnected), true); + } + assert.equal(await region.locator(".track-row").count(), total); + assert.equal(await region.locator(".library-sentinel").count(), 0); + } + try { await page.goto(base); await page.getByLabel("Host", { exact: true }).fill("https://search.example.test"); @@ -72,215 +87,111 @@ test("Search responsive layout and native actions", async () => { const input = page.getByRole("searchbox", { name: "Search library" }); await input.waitFor(); assert.equal(await input.evaluate((node) => node === document.activeElement), true); - await input.fill("Search fixture"); - const artists = page.getByRole("region", { name: "Artists", exact: true }); - const tracks = page.getByRole("region", { name: "Tracks", exact: true }); - await tracks.locator(".track-row").first().waitFor(); - assert.equal(await artists.locator(".artwork-placeholder").isVisible(), true); - const options = tracks.getByRole("button", { - name: `Open menu for ${songs[1].title}`, - exact: true, - }); - for (const width of [320, 768, 1280]) { - await page.setViewportSize({ width, height: 900 }); - await options.filter({ visible: true }).click(); - const panel = page.locator(width > 800 ? "#search-menu-popover" : "#search-menu"); - await panel.waitFor({ state: "visible" }); - assert.equal(await panel.getByRole("heading").textContent(), songs[1].title); - await page.keyboard.press("Escape"); - assert.equal( - await options.filter({ visible: true }).evaluate((node) => node === document.activeElement), - true, - ); - assert.equal( - await page.evaluate( - () => document.documentElement.scrollWidth <= document.documentElement.clientWidth, - ), - true, - ); - } - // Long press uses the sheet even on desktop, with focus restored on dismissal. - const target = tracks.getByRole("button", { name: `Play ${songs[2].title}`, exact: true }); - await target.scrollIntoViewIfNeeded(); - const box = await target.boundingBox(); - await page.mouse.move(box.x + 8, box.y + 8); - await page.mouse.down(); - const sheet = page.locator("#search-menu"); - await sheet.waitFor({ state: "visible" }); - await page.mouse.up(); - assert.equal(await sheet.evaluate((node) => node.matches(":modal")), true); - assert.equal(await sheet.getByRole("heading").textContent(), songs[2].title); - await sheet.getByRole("button", { name: "Close menu" }).click(); - assert.equal(await target.evaluate((node) => node === document.activeElement), true); - await page.setViewportSize({ width: 393, height: 852 }); - await options.filter({ visible: true }).click(); - await sheet.waitFor({ state: "visible" }); - const handle = await sheet.locator(".dialog-handle").boundingBox(); - const touch = await page.context().newCDPSession(page); - const point = { x: handle.x + handle.width / 2, y: handle.y + handle.height / 2 }; - await touch.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [point] }); - for (const offset of [20, 50, 90, 140]) { - await touch.send("Input.dispatchTouchEvent", { - type: "touchMove", - touchPoints: [{ ...point, y: point.y + offset }], - }); - } - await touch.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); - await sheet.waitFor({ state: "hidden" }); - await touch.detach(); - await page.setViewportSize({ width: 320, height: 900 }); - await page.evaluate(() => { - document.documentElement.style.fontSize = "200%"; - }); - assert.equal( - await page.evaluate( - () => document.documentElement.scrollWidth <= document.documentElement.clientWidth, - ), - true, - ); - await page.evaluate(() => { - document.documentElement.style.fontSize = ""; - }); - await page.setViewportSize({ width: 1280, height: 900 }); - await input.fill("Search fixture"); const chips = ["Artist", "Album", "Track"].map((name) => page.getByRole("button", { name, exact: true }), ); + const groups = ["Artists", "Albums", "Tracks"].map((name) => + page.getByRole("region", { name, exact: true }), + ); + const tracks = groups[2]; + await input.fill("Search fixture"); for (let mask = 0; mask < 8; mask++) { - for (let i = 0; i < chips.length; i++) { + for (let i = 0; i < 3; i++) { if (((await chips[i].getAttribute("aria-pressed")) === "true") !== !!(mask & (1 << i))) await chips[i].click(); } - const count = [0, 1, 2].filter((i) => mask & (1 << i)).length; - assert.equal( - await page.locator('section[aria-label="Artists"]').count(), - !mask || mask & 1 ? 1 : 0, - ); - assert.equal( - await page.locator('section[aria-label="Albums"]').count(), - !mask || mask & 2 ? 1 : 0, - ); - assert.equal( - await page.locator('section[aria-label="Tracks"]').count(), - !mask || mask & 4 ? 1 : 0, - ); - assert.equal(await page.locator(".virtual-list").count(), count === 1 ? 1 : 0); + for (let i = 0; i < 3; i++) + assert.equal(await groups[i].count(), !mask || mask & (1 << i) ? 1 : 0); + if (!mask || mask === 7) assert.equal(await tracks.locator(".track-row").count(), 3); + if (mask === 4) assert.equal(await tracks.locator(".track-row").count(), 48); } await chips[0].click(); await chips[1].click(); // Track only. await chips[2].focus(); await page.keyboard.press("Space"); assert.equal(await chips[2].getAttribute("aria-pressed"), "false"); - assert.equal(await chips[2].evaluate((node) => node === document.activeElement), true); await page.keyboard.press("Enter"); assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); + assert.equal(await chips[2].evaluate((node) => node === document.activeElement), true); await input.fill(""); - await page.locator('.virtual-list li[aria-setsize="1500"]').first().waitFor(); - assert.equal(await tracks.locator(".metadata").first().textContent(), "1500"); - const rowCount = async () => tracks.locator(".track-row").count(); - assert.ok((await rowCount()) < 40); + assert.equal(await tracks.locator(".track-row").count(), 48); + assert.equal(await tracks.locator("header .metadata").textContent(), "150"); assert.equal(await page.getByRole("button", { name: "Show more tracks" }).count(), 0); - const browseURL = page.url(); - assert.ok(browseURL.includes("type=track")); - await page.reload(); - await page.locator('.virtual-list li[aria-setsize="1500"]').first().waitFor(); - assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); - // Sequential Tab crosses the virtual window, not straight out of the list. - const lastMounted = page.locator(".virtual-list li").last(); - const lastIndex = Number(await lastMounted.getAttribute("data-index")); - await lastMounted - .getByRole("button", { name: /^Open menu/ }) - .filter({ visible: true }) - .focus(); - await page.keyboard.press("Tab"); - assert.equal( - await page.evaluate(() => Number(document.activeElement.closest("li").dataset.index)), - lastIndex + 1, - ); - await page.keyboard.press("Shift+Tab"); - assert.equal( - await page.evaluate(() => Number(document.activeElement.closest("li").dataset.index)), - lastIndex, - ); - // Open menus keep their invoker mounted even when it leaves the window. - await page.evaluate(() => window.scrollTo(0, 0)); - await wait(150); - const firstOptions = tracks + + // Native menu behavior and utility-only layout at desktop and narrow widths. + const options = tracks .getByRole("button", { name: `Open menu for ${songs[0].title}`, exact: true }) .filter({ visible: true }); - await firstOptions.click(); - await page.locator("#search-menu-popover").waitFor({ state: "visible" }); - await input.click(); - await page.locator("#search-menu-popover").waitFor({ state: "hidden" }); - await wait(100); - assert.equal(await input.evaluate((node) => node === document.activeElement), true); - await firstOptions.click(); - await page.locator("#search-menu-popover").waitFor({ state: "visible" }); - if (screenshots) await page.screenshot({ path: `${screenshots}/search-desktop-menu.png` }); - await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); - await wait(200); - assert.equal(await firstOptions.count(), 1); - await page.keyboard.press("Escape"); - await wait(100); - assert.equal(await firstOptions.evaluate((node) => node === document.activeElement), true); - assert.ok(await firstOptions.evaluate((node) => node.getBoundingClientRect().bottom > 0)); - await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); - await wait(200); - await tracks.getByRole("button", { name: `Play ${songs[1499].title}`, exact: true }).waitFor(); - assert.ok((await rowCount()) < 40); - await page.evaluate(() => window.scrollTo(0, 0)); - await wait(200); - assert.ok((await rowCount()) < 40); - // Wrapped measurements do not overlap and resize remains bounded. for (const width of [1280, 320]) { await page.setViewportSize({ width, height: 900 }); - await wait(200); - const geometry = await page.locator(".virtual-list li").evaluateAll((nodes) => - nodes.map((node) => { - const r = node.getBoundingClientRect(); - return { top: r.top, bottom: r.bottom }; - }), - ); - for (let i = 1; i < geometry.length; i++) - assert.ok(geometry[i].top >= geometry[i - 1].bottom - 1); - assert.equal( - await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), - true, - ); await chips[2].focus(); if (screenshots) await page.screenshot({ path: `${screenshots}/search-${width === 320 ? "narrow" : "desktop"}.png`, }); - if (width === 320) { - await firstOptions.click(); - await sheet.waitFor({ state: "visible" }); - if (screenshots) await page.screenshot({ path: `${screenshots}/search-narrow-menu.png` }); - await page.keyboard.press("Escape"); - assert.equal(await firstOptions.evaluate((node) => node === document.activeElement), true); - await page.evaluate(() => { - document.documentElement.style.fontSize = "200%"; - }); - await wait(200); - assert.equal( - await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), - true, - ); - assert.ok((await rowCount()) < 40); - await page.evaluate(() => { - document.documentElement.style.fontSize = ""; + await options.click(); + const panel = page.locator(width > 800 ? "#search-menu-popover" : "#search-menu"); + await panel.waitFor({ state: "visible" }); + assert.equal(await panel.getByRole("heading").textContent(), songs[0].title); + if (screenshots) + await page.screenshot({ + path: `${screenshots}/search-${width === 320 ? "narrow" : "desktop"}-menu.png`, }); - } + await page.keyboard.press("Escape"); + assert.equal(await options.evaluate((node) => node === document.activeElement), true); + assert.equal( + await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), + true, + ); } - // Typing replaces; chips push; Back/Forward and direct URLs remain authoritative. + await page.evaluate(() => { + document.documentElement.style.fontSize = "200%"; + }); + if (screenshots) await page.screenshot({ path: `${screenshots}/search-narrow-enlarged.png` }); + assert.equal( + await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), + true, + ); + await page.evaluate(() => { + document.documentElement.style.fontSize = ""; + }); + await page.setViewportSize({ width: 1280, height: 900 }); + // Long press still opens the ordinary shared sheet. + const target = tracks.getByRole("button", { name: `Play ${songs[1].title}`, exact: true }); + await target.scrollIntoViewIfNeeded(); + const box = await target.boundingBox(); + await page.mouse.move(box.x + 8, box.y + 8); + await page.mouse.down(); + const sheet = page.locator("#search-menu"); + await sheet.waitFor({ state: "visible" }); + await page.mouse.up(); + assert.equal(await sheet.getByRole("heading").textContent(), songs[1].title); + await sheet.getByRole("button", { name: "Close menu" }).click(); + assert.equal(await target.evaluate((node) => node === document.activeElement), true); + + // Loaded rows accumulate; both browse and matching lists reach the final record. + await loadAll(tracks, 150); + await tracks.getByRole("button", { name: `Play ${songs[149].title}`, exact: true }).waitFor(); + await input.fill("Search fixture"); + assert.equal(await tracks.locator(".track-row").count(), 48); + assert.equal(await input.evaluate((node) => node === document.activeElement), true); + await loadAll(tracks, 150); + await page.reload(); + await input.waitFor(); + assert.equal(await input.inputValue(), "Search fixture"); + assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); + assert.equal(await tracks.locator(".track-row").count(), 48); + + // Typing replaces history; chips push. URL criteria survive traversal and reload. const special = "Beyoncé 東京 + & % / ? #"; const before = await page.evaluate(() => navigation.entries().length); await input.fill(special); await page.waitForURL( - (url) => new URLSearchParams(url.search.split("&").slice(1).join("&")).get("q") === special, + (url) => + new URLSearchParams(url.search.slice(url.search.indexOf("&") + 1)).get("q") === special, ); assert.equal(await page.evaluate(() => navigation.entries().length), before); - if (screenshots) await page.screenshot({ path: `${screenshots}/search-no-matches.png` }); + assert.equal(await input.evaluate((node) => node === document.activeElement), true); await chips[0].click(); await page.goBack(); assert.equal(await input.inputValue(), special); @@ -290,72 +201,30 @@ test("Search responsive layout and native actions", async () => { await page.goto(`${base}/?/search&type=track&q=Search+fixture#search-anchor`); await tracks.locator(".track-row").first().waitFor(); assert.equal(await input.inputValue(), "Search fixture"); - assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); assert.equal(new URL(page.url()).hash, "#search-anchor"); - await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); - await wait(200); - assert.ok((await rowCount()) < 40); - // Single-type matches reach the actual final result too (score order is deterministic). - await input.fill("Search fixture track 1499"); - await tracks.getByRole("button", { name: `Play ${songs[1499].title}`, exact: true }).waitFor(); - assert.equal(await input.evaluate((node) => node === document.activeElement), true); - // Result navigation and Back restore URL criteria; a bare Search link resets them. - await chips[2].click(); - await chips[0].click(); - await input.fill("Search fixture"); - await artists.getByRole("link", { name: artist.name, exact: true }).click(); - await page.goBack(); - await input.waitFor(); - assert.equal(await input.inputValue(), "Search fixture"); - assert.equal(await chips[0].getAttribute("aria-pressed"), "true"); await page.locator('a[href="?/search"]').filter({ visible: true }).click(); assert.equal(await input.inputValue(), ""); - assert.equal(await chips[0].getAttribute("aria-pressed"), "false"); - for (const [i, group] of [ - [0, "Artists"], - [1, "Albums"], - ]) { + assert.equal(await chips[2].getAttribute("aria-pressed"), "false"); + + for (const i of [0, 1]) { await chips[i].click(); - const region = page.getByRole("region", { name: group, exact: true }); - await region.locator('.virtual-list li[aria-setsize="1500"]').first().waitFor(); - await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); - await wait(200); - assert.equal( - await region.locator(".virtual-list li").last().getAttribute("aria-posinset"), - "1500", - ); - const lastLink = region.locator(".virtual-list li").last().getByRole("link"); - await lastLink.waitFor(); - assert.ok((await region.locator(".track-row").count()) < 40); - if (i === 1) { - const y = await page.evaluate(() => scrollY); - await lastLink.click(); - await page.goBack(); - await lastLink.waitFor(); - assert.ok((await page.evaluate(() => scrollY)) > y * 0.8); - assert.equal(await chips[i].getAttribute("aria-pressed"), "true"); - } + assert.equal(await groups[i].locator(".track-row").count(), 48); + await loadAll(groups[i], 150); + const lastLink = groups[i].locator(".track-row").last().getByRole("link"); + await lastLink.click(); + await page.goBack(); + await input.waitFor(); + assert.equal(await chips[i].getAttribute("aria-pressed"), "true"); await input.fill("Directory"); - await region.locator('.virtual-list li[aria-setsize="1499"]').first().waitFor(); - await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); - await wait(200); - assert.ok((await region.locator(".track-row").count()) < 40); - assert.equal( - await region.locator(".virtual-list li").last().getAttribute("aria-posinset"), - "1499", - ); + assert.equal(await groups[i].locator(".track-row").count(), 48); + assert.equal(await groups[i].locator("header .metadata").textContent(), "149"); + await loadAll(groups[i], 149); await input.fill(""); await chips[i].click(); } - // Incoming same-route anchors must not inherit a deeply scrolled virtual window. - // Keep the anchor at the current viewport so clicking it cannot mask the bug - // by scrolling the page to the search controls before navigation. + // Real same-route links reset the result view without a search-specific router API. await chips[2].click(); - await tracks.locator('.virtual-list li[aria-setsize="1500"]').first().waitFor(); - await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight / 2)); - await wait(200); - const deepScroll = await page.evaluate(() => scrollY); - assert.ok(deepScroll > 10000); + await loadAll(tracks, 150); await page.evaluate(() => { const link = document.createElement("a"); link.id = "incoming-search-link"; @@ -370,34 +239,22 @@ test("Search responsive layout and native actions", async () => { document.body.append(link); }); await page.getByRole("link", { name: "Browse directory albums", exact: true }).click(); - const firstAlbum = page.locator( - 'section[aria-label="Albums"] .virtual-list li[data-index="0"]', + await groups[1].locator(".track-row").first().waitFor(); + assert.ok( + await groups[1] + .locator(".track-row") + .first() + .evaluate((node) => { + const bounds = node.getBoundingClientRect(); + return bounds.top >= 0 && bounds.top < innerHeight; + }), ); - await firstAlbum.waitFor(); - await page.waitForFunction(() => { - const first = document.querySelector( - 'section[aria-label="Albums"] .virtual-list li[data-index="0"]', - ); - if (!first) return false; - const bounds = first.getBoundingClientRect(); - return scrollY < 200 && bounds.top >= 0 && bounds.top < innerHeight; - }); - assert.equal(await input.inputValue(), "Directory"); - assert.equal(await chips[1].getAttribute("aria-pressed"), "true"); await page.goBack(); - await tracks.locator(".track-row").first().waitFor(); assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); assert.equal(await input.inputValue(), ""); - assert.ok((await page.evaluate(() => scrollY)) > deepScroll * 0.8); await page.goForward(); - await firstAlbum.waitFor(); - assert.ok( - await firstAlbum.evaluate((node) => { - const bounds = node.getBoundingClientRect(); - return bounds.top >= 0 && bounds.top < innerHeight; - }), - ); - await page.locator("#incoming-search-link").evaluate((node) => node.remove()); + assert.equal(await chips[1].getAttribute("aria-pressed"), "true"); + assert.equal(await input.inputValue(), "Directory"); assert.deepEqual(errors, []); } finally { await browser.close(); diff --git a/tests/router.test.ts b/tests/router.test.ts index c856e46..31bd867 100644 --- a/tests/router.test.ts +++ b/tests/router.test.ts @@ -113,16 +113,9 @@ describe("router", () => { }, ); - it.each([ - { navigationType: "push", local: false }, - { navigationType: "replace", local: false }, - { navigationType: "push", local: true }, - { navigationType: "replace", local: true }, - { navigationType: "traverse", local: false }, - { navigationType: "traverse", local: true }, - ])( - "updates same-route search $navigationType (local: $local) with appropriate scroll handling", - async ({ navigationType, local }) => { + it.each(["push", "replace", "traverse"])( + "updates same-route search %s with native scrolling and preserved focus", + async (navigationType) => { const { navigation } = setup("/search&type=artist&q=one"); expect(route.parameters.get("q")).toBe("one"); const start = vi.fn(); @@ -131,7 +124,6 @@ describe("router", () => { navigation.dispatchEvent( Object.assign(navigationEvent(), { navigationType, - info: local ? { preserveScroll: true } : undefined, canIntercept: true, destination: { url: new URL("?/search&type=track&q=two#anchor", window.location.href).href, @@ -143,9 +135,7 @@ describe("router", () => { expect(route.parameters.get("q")).toBe("two"); expect(route.parameters.getAll("type")).toEqual(["track"]); expect(intercept.mock.calls[0][0]).toMatchObject({ focusReset: "manual" }); - if (local && navigationType !== "traverse") - expect(intercept.mock.calls[0][0]).toMatchObject({ scroll: "manual" }); - else expect(intercept.mock.calls[0][0]).not.toHaveProperty("scroll"); + expect(intercept.mock.calls[0][0]).not.toHaveProperty("scroll"); expect(start).not.toHaveBeenCalled(); }, ); @@ -186,15 +176,6 @@ describe("router", () => { expect(navigation.navigate).toHaveBeenLastCalledWith("?/player", { history: "replace" }); }); - it("marks local search updates without changing ordinary navigation options", () => { - const navigation = installNavigation("/search&type=artist"); - navigate("/search&type=album", "push", { preserveScroll: true }); - expect(navigation.navigate).toHaveBeenCalledWith("?/search&type=album", { - history: "push", - info: { preserveScroll: true }, - }); - }); - it.each(["/webapp/", "/webapp/?section"])("renders the fallback without rewriting %s", (url) => { const { navigation, target } = setup("/library", url); expect(window.location.href).toBe(new URL(url, window.location.origin).href); diff --git a/tests/search-filters.test.ts b/tests/search-filters.test.ts index e6e6ba5..391014c 100644 --- a/tests/search-filters.test.ts +++ b/tests/search-filters.test.ts @@ -1,12 +1,14 @@ // @vitest-environment happy-dom import { flushSync, mount, unmount } from "svelte"; -import { describe, expect, it, vi } from "vitest"; -import Search, { createSearchState } from "../src/_search.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"; -function fixture() { - const artists = Array.from({ length: 1500 }, (_, i) => ({ +afterEach(() => vi.unstubAllGlobals()); + +function fixture(count = 1500) { + const artists = Array.from({ length: count }, (_, i) => ({ id: `a${i}`, name: `Fixture artist ${i}`, })); @@ -37,11 +39,57 @@ function fixture() { covers: {}, trackEngine: { getStatus: () => "downloaded" }, playback: { toggleTrack: vi.fn(), replaceQueueAndPlay: vi.fn(), enqueue: vi.fn() }, - state: createSearchState(), } as unknown as ComponentProps; } describe("independent search filters", () => { + it.each([0, 1, 2])( + "appends batches for type %s and restarts on URL criteria changes", + async (type) => { + 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]")[type].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"); + 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(); const offlineProps = { @@ -58,7 +106,9 @@ describe("independent search filters", () => { trackChip.click(); flushSync(); expect(target.querySelectorAll(".track-row")).toHaveLength(1); - expect(target.querySelector("li[aria-setsize]")?.getAttribute("aria-setsize")).toBe("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 1499"); play.click(); @@ -75,7 +125,7 @@ describe("independent search filters", () => { } }); it.each(Array.from({ length: 8 }, (_, mask) => mask))( - "supports combination %s, previews and full bounded browse", + "supports combination %s, previews and single-type batches", async (mask) => { const props = fixture(); const target = document.createElement("main"); @@ -96,11 +146,9 @@ describe("independent search filters", () => { ); const selected = chips.filter((_, i) => mask & (1 << i)).length; if (selected === 1) { - expect(target.querySelector(".virtual-list")).not.toBeNull(); - expect(target.querySelectorAll(".track-row").length).toBeLessThan(30); - expect(target.querySelector("li[aria-setsize]")?.getAttribute("aria-setsize")).toBe( - "1500", - ); + expect(target.querySelectorAll(".track-row")).toHaveLength(48); + expect(target.querySelector(".library-sentinel")).not.toBeNull(); + expect(target.querySelector("section[aria-label] header")?.textContent).toContain("1500"); expect(target.textContent).not.toContain("Show more"); } else expect(target.textContent).toContain("Type to find music"); const input = target.querySelector("input")!; @@ -108,7 +156,8 @@ describe("independent search filters", () => { input.dispatchEvent(new Event("input", { bubbles: true })); flushSync(); expect(target.querySelectorAll("section[aria-label]").length).toBe(selected || 3); - expect(target.querySelectorAll(".virtual-list").length).toBe(selected === 1 ? 1 : 0); + 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) => { diff --git a/tests/search-page.test.ts b/tests/search-page.test.ts index 2826656..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,7 +201,7 @@ 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 { diff --git a/tests/search-test-app.svelte b/tests/search-test-app.svelte index 57c5526..59deddf 100644 --- a/tests/search-test-app.svelte +++ b/tests/search-test-app.svelte @@ -1,10 +1,20 @@ -{#if visible}{/if} +{#if visible}{/if} From 203e95dd34876eb2e03cf9c0e7c55ba33e28d87a Mon Sep 17 00:00:00 2001 From: Bogdan Chadkin Date: Wed, 11 Nov 2026 18:20:09 +0100 Subject: [PATCH 3/8] Keep query route parsing in router --- src/_search.svelte | 21 ++++++++++++++- src/router.svelte | 25 ++++++++++++------ src/search-url.ts | 30 --------------------- tests/browser/search.test.cjs | 28 ++++++++++++++++++-- tests/router.test.ts | 42 ++++++++++++++++++++++++++--- tests/search-test-app.svelte | 5 ++-- tests/search-url.test.ts | 34 ------------------------ tests/search.test.ts | 50 ++++++++++++++++++++++++++++++++++- 8 files changed, 153 insertions(+), 82 deletions(-) delete mode 100644 src/search-url.ts delete mode 100644 tests/search-url.test.ts diff --git a/src/_search.svelte b/src/_search.svelte index d30906b..8104132 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]; @@ -123,7 +143,6 @@ diff --git a/tests/search-url.test.ts b/tests/search-url.test.ts deleted file mode 100644 index 8eef6ae..0000000 --- a/tests/search-url.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { parseSearch, searchHref, searchTypes, splitRoute } from "../src/search-url"; - -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/"); - const { path, parameters } = splitRoute(url.search); - expect(path).toBe("/search"); - expect(parseSearch(parameters)).toEqual({ query, types }); - expect(url.pathname).toBe("/demo/"); - expect(url.hash).toBe(""); - } - }); - it("ignores unknown types, deduplicates and canonicalizes, and uses the first q", () => { - const criteria = parseSearch( - new URLSearchParams("type=track&type=no&type=artist&type=track&q=first&q=second"), - ); - expect(criteria).toEqual({ query: "first", types: ["artist", "track"] }); - expect(searchHref(criteria.query, criteria.types)).toBe( - "?/search&type=artist&type=track&q=first", - ); - expect(parseSearch(new URLSearchParams("type=unknown"))).toEqual({ query: "", types: [] }); - expect(searchHref()).toBe("?/search"); - }); - it("splits literal delimiters before decoding route IDs and leaves hash separate", () => { - const url = new URL( - "https://example.test/?/library/artist/a%26b%2Fc%3Fd%23e%25&ignored=x#anchor", - ); - expect(splitRoute(url.search).path).toBe("/library/artist/a%26b%2Fc%3Fd%23e%25"); - expect(url.hash).toBe("#anchor"); - }); -}); diff --git a/tests/search.test.ts b/tests/search.test.ts index d653631..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([ From 852d03873482a3a0923d8ff9fbe66471615c6514 Mon Sep 17 00:00:00 2001 From: Bogdan Chadkin Date: Thu, 12 Nov 2026 11:38:11 +0100 Subject: [PATCH 4/8] Decouple search parameter subscription from route matching --- src/_search.svelte | 5 +- src/router.svelte | 29 ++++- tests/browser/search.test.cjs | 70 +++++++++-- tests/router-test-helpers.ts | 8 ++ tests/router.test.ts | 27 ----- tests/search-filters.test.ts | 5 + tests/search-params-test-reader.svelte.ts | 8 ++ tests/search-params.test.ts | 137 ++++++++++++++++++++++ tests/search-test-app.svelte | 7 +- 9 files changed, 244 insertions(+), 52 deletions(-) create mode 100644 tests/search-params-test-reader.svelte.ts create mode 100644 tests/search-params.test.ts diff --git a/src/_search.svelte b/src/_search.svelte index 8104132..41e67f1 100644 --- a/src/_search.svelte +++ b/src/_search.svelte @@ -142,7 +142,7 @@ From 546598ee48ca577eabd5235225ddfb337fa6164e Mon Sep 17 00:00:00 2001 From: Bogdan Chadkin Date: Thu, 12 Nov 2026 12:09:06 +0100 Subject: [PATCH 5/8] Trim redundant search coverage and simplify empty state --- src/_search.svelte | 50 ++++++------ tests/browser/search.test.cjs | 134 +++++++++++--------------------- tests/router.test.ts | 49 ++++++------ tests/search-filters.test.ts | 105 ++++++++++++------------- tests/search-params.test.ts | 140 +++++++++++----------------------- 5 files changed, 186 insertions(+), 292 deletions(-) diff --git a/src/_search.svelte b/src/_search.svelte index 41e67f1..6960fe5 100644 --- a/src/_search.svelte +++ b/src/_search.svelte @@ -373,33 +373,31 @@

Loading your library…

{:else if index.size === 0} - {#if session.localReady} -
-

- {cache.savedAt === undefined - ? "Connect your library" - : session.offlineMode - ? "No downloaded music to search." - : "Your library is empty."} -

-

- {cache.savedAt === undefined - ? "Add your music server to start searching." - : session.offlineMode - ? "Download music from the library to search offline." - : "Your music will appear here after synchronization."} -

- +
+

+ {cache.savedAt === undefined + ? "Connect your library" + : session.offlineMode + ? "No downloaded music to search." + : "Your library is empty."} +

+

+ {cache.savedAt === undefined + ? "Add your music server to start searching." + : session.offlineMode + ? "Download music from the library to search offline." + : "Your music will appear here after synchronization."} +

+ - {/if} +
{:else if !matches.query && !singleType}

Type to find music in your library. diff --git a/tests/browser/search.test.cjs b/tests/browser/search.test.cjs index 6ba8de0..de3f928 100644 --- a/tests/browser/search.test.cjs +++ b/tests/browser/search.test.cjs @@ -4,7 +4,6 @@ const { test } = require("node:test"); const { chromium } = require("playwright"); const base = process.env.PREVIEW_URL ?? "http://127.0.0.1:5173"; const screenshots = process.env.SCREENSHOT_DIR; -const forcePolyfill = process.env.FORCE_NAVIGATION_POLYFILL === "1"; test("Search filters, incremental lists, URLs and native actions", async () => { const browser = await chromium.launch({ headless: true }); @@ -12,10 +11,6 @@ test("Search filters, incremental lists, URLs and native actions", async () => { viewport: { width: 1280, height: 900 }, reducedMotion: "reduce", }); - if (forcePolyfill) - await page.addInitScript(() => { - delete window.navigation; - }); const errors = []; page.on("pageerror", (error) => errors.push(error.message)); const artist = { @@ -28,7 +23,7 @@ test("Search filters, incremental lists, URLs and native actions", async () => { artists: [artist], year: 2024, }; - const directoryArtists = Array.from({ length: 149 }, (_, i) => ({ + const directoryArtists = Array.from({ length: 2 }, (_, i) => ({ id: `directory-artist-${i}`, name: `Directory artist ${i}`, })); @@ -38,7 +33,7 @@ test("Search filters, incremental lists, URLs and native actions", async () => { artists: [a], year: 2024, })); - const songs = Array.from({ length: 150 }, (_, i) => ({ + const songs = Array.from({ length: 120 }, (_, i) => ({ id: `track-${i}`, title: `Search fixture track ${i}${i === 0 ? " — a long title with naturally wrapped lines and Unicode Beyoncé 東京" : ""}`, albumId: album.id, @@ -71,28 +66,8 @@ test("Search filters, incremental lists, URLs and native actions", async () => { }); }); - async function loadAll(region, total) { - const first = await region.locator(".track-row").first().elementHandle(); - while ((await region.locator(".track-row").count()) < total) { - const count = await region.locator(".track-row").count(); - await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); - await region - .locator(".track-row") - .nth(Math.min(count + 47, total - 1)) - .waitFor(); - assert.equal(await first.evaluate((node) => node.isConnected), true); - } - assert.equal(await region.locator(".track-row").count(), total); - assert.equal(await region.locator(".library-sentinel").count(), 0); - } - try { - await page.goto(forcePolyfill ? `${base}/?/settings` : base); - await page.getByLabel("Host", { exact: true }).waitFor(); - assert.equal( - await page.evaluate(() => navigation.constructor.toString().includes("[native code]")), - !forcePolyfill, - ); + await page.goto(base); await page.getByLabel("Host", { exact: true }).fill("https://search.example.test"); await page.getByLabel("Username", { exact: true }).fill("listener"); await page.getByLabel("Password", { exact: true }).fill("fictional-password"); @@ -101,9 +76,7 @@ test("Search filters, incremental lists, URLs and native actions", async () => { await page.locator('a[href="?/search"]').filter({ visible: true }).click(); const input = page.getByRole("searchbox", { name: "Search library" }); await input.waitFor(); - // The polyfill resets focus after page navigation; exercise in-place focus below. - if (forcePolyfill) await input.focus(); - else assert.equal(await input.evaluate((node) => node === document.activeElement), true); + assert.equal(await input.evaluate((node) => node === document.activeElement), true); const chips = ["Artist", "Album", "Track"].map((name) => page.getByRole("button", { name, exact: true }), ); @@ -112,18 +85,8 @@ test("Search filters, incremental lists, URLs and native actions", async () => { ); const tracks = groups[2]; await input.fill("Search fixture"); - for (let mask = 0; mask < 8; mask++) { - for (let i = 0; i < 3; i++) { - if (((await chips[i].getAttribute("aria-pressed")) === "true") !== !!(mask & (1 << i))) - await chips[i].click(); - } - for (let i = 0; i < 3; i++) - assert.equal(await groups[i].count(), !mask || mask & (1 << i) ? 1 : 0); - if (!mask || mask === 7) assert.equal(await tracks.locator(".track-row").count(), 3); - if (mask === 4) assert.equal(await tracks.locator(".track-row").count(), 48); - } - await chips[0].click(); - await chips[1].click(); // Track only. + assert.equal(await tracks.locator(".track-row").count(), 3); + await chips[2].click(); await chips[2].focus(); await page.keyboard.press("Space"); assert.equal(await chips[2].getAttribute("aria-pressed"), "false"); @@ -132,7 +95,7 @@ test("Search filters, incremental lists, URLs and native actions", async () => { assert.equal(await chips[2].evaluate((node) => node === document.activeElement), true); await input.fill(""); assert.equal(await tracks.locator(".track-row").count(), 48); - assert.equal(await tracks.locator("header .metadata").textContent(), "150"); + assert.equal(await tracks.locator("header .metadata").textContent(), "120"); assert.equal(await page.getByRole("button", { name: "Show more tracks" }).count(), 0); // Native menu behavior and utility-only layout at desktop and narrow widths. @@ -186,13 +149,23 @@ test("Search filters, incremental lists, URLs and native actions", async () => { await sheet.getByRole("button", { name: "Close menu" }).click(); assert.equal(await target.evaluate((node) => node === document.activeElement), true); - // Loaded rows accumulate; both browse and matching lists reach the final record. - await loadAll(tracks, 150); + // One real observer-driven completion: loaded Track batches retain earlier rows. + const first = await tracks.locator(".track-row").first().elementHandle(); + while ((await tracks.locator(".track-row").count()) < songs.length) { + const count = await tracks.locator(".track-row").count(); + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + await tracks + .locator(".track-row") + .nth(Math.min(count + 47, songs.length - 1)) + .waitFor(); + assert.equal(await first.evaluate((node) => node.isConnected), true); + } + assert.equal(await tracks.locator(".library-sentinel").count(), 0); await page.evaluate(() => { location.hash = "search-anchor"; }); await page.waitForURL((url) => url.hash === "#search-anchor"); - assert.equal(await tracks.locator(".track-row").count(), 150); + assert.equal(await tracks.locator(".track-row").count(), 120); await page.evaluate(async () => { const cancel = (event) => { if (event.destination.url.includes("q=uncommitted")) event.preventDefault(); @@ -207,12 +180,12 @@ test("Search filters, incremental lists, URLs and native actions", async () => { }); assert.equal(await input.inputValue(), ""); assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); - assert.equal(await tracks.locator(".track-row").count(), 150); - await tracks.getByRole("button", { name: `Play ${songs[149].title}`, exact: true }).waitFor(); + assert.equal(await tracks.locator(".track-row").count(), 120); + await input.fill("Search fixture track 119"); + await tracks.getByRole("button", { name: `Play ${songs[119].title}`, exact: true }).waitFor(); await input.fill("Search fixture"); assert.equal(await tracks.locator(".track-row").count(), 48); assert.equal(await input.evaluate((node) => node === document.activeElement), true); - await loadAll(tracks, 150); await page.reload(); await input.waitFor(); await tracks.locator(".track-row").first().waitFor(); @@ -246,28 +219,22 @@ test("Search filters, incremental lists, URLs and native actions", async () => { for (const i of [0, 1]) { await chips[i].click(); - assert.equal(await groups[i].locator(".track-row").count(), 48); - await loadAll(groups[i], 150); - const lastLink = groups[i].locator(".track-row").last().getByRole("link"); - await lastLink.click(); - await page.goBack(); - await input.waitFor(); - assert.equal(await chips[i].getAttribute("aria-pressed"), "true"); + assert.equal(await groups[i].locator(".track-row").count(), 3); await input.fill("Directory"); - assert.equal(await groups[i].locator(".track-row").count(), 48); - assert.equal(await groups[i].locator("header .metadata").textContent(), "149"); - await loadAll(groups[i], 149); + assert.equal(await groups[i].locator(".track-row").count(), 2); + assert.equal(await groups[i].locator("header .metadata").textContent(), "2"); await input.fill(""); await chips[i].click(); } // Real same-route links reset the result view without a search-specific router API. await chips[2].click(); - await loadAll(tracks, 150); + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + await tracks.locator(".track-row").nth(95).waitFor(); await page.evaluate(() => { const link = document.createElement("a"); link.id = "incoming-search-link"; - link.href = "?/search&type=album&q=Directory"; - link.textContent = "Browse directory albums"; + link.href = "?/search&type=track&q=Search+fixture"; + link.textContent = "Search matching tracks"; Object.assign(link.style, { position: "fixed", bottom: "16px", @@ -276,25 +243,23 @@ test("Search filters, incremental lists, URLs and native actions", async () => { }); document.body.append(link); }); - await page.getByRole("link", { name: "Browse directory albums", exact: true }).click(); - await groups[1].locator(".track-row").first().waitFor(); - // Native automatic scrolling is not implemented by the Navigation polyfill. - if (!forcePolyfill) - assert.ok( - await groups[1] - .locator(".track-row") - .first() - .evaluate((node) => { - const bounds = node.getBoundingClientRect(); - return bounds.top >= 0 && bounds.top < innerHeight; - }), - ); + await page.getByRole("link", { name: "Search matching tracks", exact: true }).click(); + await tracks.locator(".track-row").first().waitFor(); + assert.ok( + await tracks + .locator(".track-row") + .first() + .evaluate((node) => { + const bounds = node.getBoundingClientRect(); + return bounds.top >= 0 && bounds.top < innerHeight; + }), + ); await page.goBack(); assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); assert.equal(await input.inputValue(), ""); await page.goForward(); - assert.equal(await chips[1].getAttribute("aria-pressed"), "true"); - assert.equal(await input.inputValue(), "Directory"); + assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); + assert.equal(await input.inputValue(), "Search fixture"); // Router matches raw tokens while Search reads only criteria from the full params. await page.goto( `${base}/?/search=&unknown=keep&type=no&type=track&type=track&q=Search+fixture&q=ignored`, @@ -303,17 +268,10 @@ test("Search filters, incremental lists, URLs and native actions", async () => { assert.equal(await input.inputValue(), "Search fixture"); assert.equal(await chips[2].getAttribute("aria-pressed"), "true"); assert.equal(await chips[0].getAttribute("aria-pressed"), "false"); - await input.fill("Search fixture track 149"); + await input.fill("Search fixture track 119"); assert.equal(await input.evaluate((node) => node === document.activeElement), true); - // Native History can commit a non-route query that Router deliberately ignores. - // The polyfill patches History via navigation, so use its ordinary route URL. - await page.evaluate((polyfill) => { - history.pushState( - null, - "", - polyfill ? "?/search&type=album&q=Directory" : "?type=album&q=Directory", - ); - }, forcePolyfill); + // History can commit a non-route query that Router deliberately ignores. + await page.evaluate(() => history.pushState(null, "", "?type=album&q=Directory")); await page.waitForFunction( () => document.querySelector("#library-search").value === "Directory", ); diff --git a/tests/router.test.ts b/tests/router.test.ts index b1b4ff3..75ee51a 100644 --- a/tests/router.test.ts +++ b/tests/router.test.ts @@ -122,32 +122,29 @@ describe("router", () => { }, ); - it.each(["push", "replace", "traverse"])( - "updates same-route search %s with native scrolling and preserved focus", - async (navigationType) => { - 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, - 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("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"); diff --git a/tests/search-filters.test.ts b/tests/search-filters.test.ts index 43de887..85b2d8a 100644 --- a/tests/search-filters.test.ts +++ b/tests/search-filters.test.ts @@ -7,7 +7,7 @@ import type { ComponentProps } from "svelte"; afterEach(() => vi.unstubAllGlobals()); -function fixture(count = 1500) { +function fixture(count = 120) { const artists = Array.from({ length: count }, (_, i) => ({ id: `a${i}`, name: `Fixture artist ${i}`, @@ -43,64 +43,59 @@ function fixture(count = 1500) { } describe("independent search filters", () => { - it.each([0, 1, 2])( - "appends batches for type %s and restarts on URL criteria changes", - async (type) => { - 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]")[type].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); + 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; } - expect(target.querySelector(".library-sentinel")).toBeNull(); - expect(target.textContent).toContain("119"); - window.navigation.navigate(`?/search&type=${["artist", "album", "track"][type]}#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 })); + 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(48); - } finally { - await unmount(app); - target.remove(); + 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(); + const props = fixture(3); const offlineProps = { ...props, session: { localReady: true, offlineMode: true }, - trackEngine: { getStatus: (id: string) => (id === "t1499" ? "downloaded" : "idle") }, + trackEngine: { getStatus: (id: string) => (id === "t2" ? "downloaded" : "idle") }, } as unknown as ComponentProps; const target = document.createElement("main"); document.body.append(target); @@ -115,9 +110,9 @@ describe("independent search filters", () => { "1", ); const play = target.querySelector(".track-row button.link-target")!; - expect(play.getAttribute("aria-label")).toBe("Play Fixture track 1499"); + expect(play.getAttribute("aria-label")).toBe("Play Fixture track 2"); play.click(); - expect(props.playback.toggleTrack).toHaveBeenCalledWith("t1499", ["t1499"]); + expect(props.playback.toggleTrack).toHaveBeenCalledWith("t2", ["t2"]); const input = target.querySelector("input")!; input.value = "Fixture track 0"; input.dispatchEvent(new Event("input", { bubbles: true })); @@ -153,7 +148,7 @@ describe("independent search filters", () => { 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("1500"); + 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")!; diff --git a/tests/search-params.test.ts b/tests/search-params.test.ts index d620d03..b55305b 100644 --- a/tests/search-params.test.ts +++ b/tests/search-params.test.ts @@ -5,41 +5,23 @@ import { getSearchParameters } from "../src/router.svelte"; import { observeSearchParameters } from "./search-params-test-reader.svelte"; import { installNavigation, navigationEvent } from "./router-test-helpers"; -const cleanups = new Set<() => void>(); -afterEach(async () => { - for (const stop of cleanups) stop(); - cleanups.clear(); - await tick(); +afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); }); -function observe(read: (parameters: URLSearchParams) => void) { - const dispose = observeSearchParameters(read); - const stop = () => { - dispose(); - cleanups.delete(stop); - }; - cleanups.add(stop); - flushSync(); - return stop; -} - -it.each(["/player", "/player=", "/player=invalid"])( - "reads full initial parameters without Router or a subscription: %s", - (path) => { - const navigation = installNavigation( - `${path}&unknown=first&type=album&type=track&q=one&q=two&unknown=last`, - ); - const add = vi.spyOn(navigation, "addEventListener"); - expect([...getSearchParameters()]).toEqual([...new URL(window.location.href).searchParams]); - expect([...getSearchParameters()][0]).toEqual([ - "/player", - path.includes("invalid") ? "invalid" : "", - ]); - expect(add).not.toHaveBeenCalled(); - }, -); +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"); @@ -54,84 +36,48 @@ it("falls back to location when no current entry URL is available", () => { expect(getSearchParameters().get("q")).toBe("fallback"); }); -it.each(["push", "replace", "traverse"])( - "observes committed %s, not attempted or canceled destinations", - (navigationType) => { - const navigation = installNavigation("/search&q=initial"); - const read = vi.fn(); - observe(read); +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(), { - navigationType, signal: controller.signal, destination: { url: new URL("?/search&q=canceled", window.location.href).href }, }), ); flushSync(); - expect(read).toHaveBeenCalledTimes(1); - navigation.commit( - "?/search=&unknown=first&type=track&type=album&q=committed&q=second&unknown=last", - ); + 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([ - ["/search", ""], - ["unknown", "first"], - ["type", "track"], - ["type", "album"], - ["q", "committed"], - ["q", "second"], - ["unknown", "last"], + ["unrouted", "one"], + ["unrouted", "two"], ]); - }, -); - -it("reacts to unintercepted commits and ignores hash-only changes", () => { - const navigation = installNavigation("/search&q=initial"); - const read = vi.fn(); - observe(read); - navigation.dispatchEvent( - Object.assign(navigationEvent(), { canIntercept: false, hashChange: true }), - ); - navigation.commit("?/search&q=initial#anchor"); - flushSync(); - expect(read).toHaveBeenCalledTimes(1); - navigation.commit("?unrouted=one&unrouted=two", false); - flushSync(); - expect([...read.mock.lastCall![0]]).toEqual([ - ["unrouted", "one"], - ["unrouted", "two"], - ]); -}); - -it("shares one lazy listener, cleans up after the last reader, and reads fresh state on resubscription", async () => { - const navigation = installNavigation("/search&q=initial"); - const add = vi.spyOn(navigation, "addEventListener"); - const remove = vi.spyOn(navigation, "removeEventListener"); - const first = vi.fn(); - const second = vi.fn(); - const stopFirst = observe(first); - const stopSecond = observe(second); - expect(add).toHaveBeenCalledTimes(1); - expect(add.mock.calls[0][0]).toBe("currententrychange"); - navigation.commit("?/search&q=both"); - flushSync(); - expect(first.mock.lastCall![0].get("q")).toBe("both"); - expect(second.mock.lastCall![0].get("q")).toBe("both"); - stopFirst(); - await tick(); - expect(remove).not.toHaveBeenCalled(); - stopSecond(); - expect(remove).not.toHaveBeenCalled(); - await tick(); - expect(remove).toHaveBeenCalledTimes(1); - expect(remove.mock.calls[0]).toEqual(add.mock.calls[0]); - navigation.commit("?/search&q=while-unsubscribed"); - const remounted = vi.fn(); - observe(remounted); - expect(add).toHaveBeenCalledTimes(2); - expect(remounted.mock.lastCall![0].get("q")).toBe("while-unsubscribed"); + 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(); + } }); From 4d001cb1bef664b285df3130156cdd6d3f4adbb1 Mon Sep 17 00:00:00 2001 From: Bogdan Chadkin Date: Thu, 12 Nov 2026 13:27:28 +0100 Subject: [PATCH 6/8] Explain derived search pagination resets --- src/_search.svelte | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/_search.svelte b/src/_search.svelte index 6960fe5..097d40c 100644 --- a/src/_search.svelte +++ b/src/_search.svelte @@ -183,13 +183,15 @@ const selectedTypes = $derived(criteria.types); const singleType = $derived(selectedTypes.length === 1); const matches = $derived(searchLibrary(index, criteria.query, singleType)); - // URL criteria and cache switches restart local batches and previews. + // User increments override these derived limits until cache or URL criteria change. + // The void reads intentionally track those dependencies so recomputation resets pagination. const pageSize = 48; let limit = $derived.by(() => { void cache; void criteria; return pageSize; }); + // Grouped previews reset on the same dependencies as the single-type batch limit. let limits = $derived.by(() => { void cache; void criteria; From 223195d2ce6a2f610ed3e44bc45aa529347971ed Mon Sep 17 00:00:00 2001 From: Bogdan Chadkin Date: Fri, 13 Nov 2026 19:48:10 +0100 Subject: [PATCH 7/8] Extract app-owned native audio transport --- CONTRIBUTING.md | 3 +- src/app.svelte | 37 +- src/audio-player.svelte | 518 +++------------------------- src/audio-transport.svelte.ts | 420 ++++++++++++++++++++++ src/playback.svelte.ts | 11 +- src/ui/player.svelte | 4 +- tests/audio-player.test.ts | 60 +++- tests/audio-transport.test.ts | 199 +++++++++++ tests/media-session.test.ts | 13 +- tests/playback-page-test-app.svelte | 36 +- tests/playback-queue.test.ts | 29 +- tests/playback.test.ts | 22 +- 12 files changed, 821 insertions(+), 531 deletions(-) create mode 100644 src/audio-transport.svelte.ts create mode 100644 tests/audio-transport.test.ts 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/app.svelte b/src/app.svelte index 941e678..b4c2c69 100644 --- a/src/app.svelte +++ b/src/app.svelte @@ -5,6 +5,7 @@ import { Playback } from "./playback.svelte"; import { Playlists } from "./playlists.svelte"; import AudioPlayer from "./audio-player.svelte"; + import { AudioTransport } from "./audio-transport.svelte"; import Player from "./ui/player.svelte"; import Atmosphere from "./ui/atmosphere.svelte"; import Loader from "./ui/loader.svelte"; @@ -51,7 +52,7 @@ const covers = new Covers(selection); const playlists = new Playlists(selection); const trackEngine = new TrackEngine({ selection }); - let player = $state>(); + let player = $state.raw(); const playback: Playback = new Playback({ selection, tracks: trackEngine, @@ -98,7 +99,20 @@ onMount(() => installLongPress()); onMount(() => installSwipeToDismiss()); - onMount(() => playback.attach(player!)); + onMount(() => { + const transport = new AudioTransport({ + onposition: (position) => playback.setPosition(position), + onended: () => playback.ended(), + onstatechange: (state) => playback.updatePlayerState(state), + }); + player = transport; + const detach = playback.attach(transport); + return () => { + detach(); + transport.dispose(); + player = undefined; + }; + }); onDestroy(() => { session.destroy(); @@ -122,16 +136,15 @@ }); -= 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)} -/> +{#if player} + = 0 && cache.queue.position > 0)} + hasNext={hasNextTrack} + onprevious={() => playback.previous()} + onnext={() => playback.next()} + /> +{/if} {#snippet settingsRoute()} 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/ui/player.svelte b/src/ui/player.svelte index a8aa7cd..233983c 100644 --- a/src/ui/player.svelte +++ b/src/ui/player.svelte @@ -7,7 +7,7 @@ import type { Cache } from "../cache.svelte"; import type { Playback } from "../playback.svelte"; import type { TrackEngine } from "../track.svelte"; - import type AudioPlayer from "../audio-player.svelte"; + import type { AudioTransport } from "../audio-transport.svelte"; import { formatDuration } from "../time"; interface Props { @@ -15,7 +15,7 @@ covers: Covers; playback: Playback; trackEngine: TrackEngine; - audio: ReturnType | undefined; + audio: AudioTransport | undefined; offlineMode: boolean; } diff --git a/tests/audio-player.test.ts b/tests/audio-player.test.ts index 0773e95..8d98747 100644 --- a/tests/audio-player.test.ts +++ b/tests/audio-player.test.ts @@ -2,12 +2,13 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { flushSync, mount, unmount } from "svelte"; import { fromStore, writable } from "svelte/store"; -import Player, { +import Player from "../src/audio-player.svelte"; +import { + AudioTransport, type PlayerTrack, type PlayerSource, - type PlayerProps, type PlayerState, -} from "../src/audio-player.svelte"; +} from "../src/audio-transport.svelte"; class AudioStub extends EventTarget { preload = ""; @@ -79,7 +80,7 @@ function setup() { const navigation = writable({ previous: true, next: true }); const availability = fromStore(navigation); const onstatechange = vi.fn<(state: PlayerState) => void>(); - const props: PlayerProps = { + const props = { onstatechange, get hasPrevious() { return availability.current.previous; @@ -92,9 +93,31 @@ function setup() { onposition: vi.fn(), onended: vi.fn(), }; - const player = mount(Player, { target: document.createElement("div"), props }); + const player = new AudioTransport(props); + const binding = mount(Player, { + target: document.createElement("div"), + props: { + ...props, + transport: player, + get hasPrevious() { + return availability.current.previous; + }, + get hasNext() { + return availability.current.next; + }, + }, + }); flushSync(); - const detach = () => unmount(player); + let bound = true; + const unbind = async () => { + if (!bound) return; + bound = false; + await unmount(binding); + }; + const detach = async () => { + player.dispose(); + await unbind(); + }; cleanups.push(detach); const item: PlayerTrack = { metadata: { title: "A", duration: 300 }, position: 0, getSource }; return { @@ -109,6 +132,7 @@ function setup() { detach, navigation, onstatechange, + unbind, }; } @@ -142,7 +166,26 @@ async function setupShortcuts() { return { toggle, dispatch, cleanup: detach }; } -describe("Player component", () => { +describe("Player browser-control binding", () => { + it("removes global handlers without unloading the independently owned transport", async () => { + const { player, audio, item, unbind, session, handlers, release, getSource } = setup(); + await player.play(item); + await unbind(); + expect(session.metadata).toBeNull(); + expect([...handlers.values()].every((handler) => handler === null)).toBe(true); + expect(player.playing).toBe(true); + expect(audio.src).toBe("blob:track"); + expect(release).not.toHaveBeenCalled(); + const event = new KeyboardEvent("keydown", { key: " ", cancelable: true }); + document.dispatchEvent(event); + expect(event.defaultPrevented).toBe(false); + player.pause(); + await player.resume(); + expect(player.playing).toBe(true); + expect(getSource).toHaveBeenCalledOnce(); + player.dispose(); + expect(release).toHaveBeenCalledOnce(); + }); it("emits complete transport states synchronously, including native pause and buffering", async () => { const { player, audio, item, getSource, onstatechange } = setup(); const source = Promise.withResolvers(); @@ -667,6 +710,7 @@ describe("Player component", () => { vi.mocked(props.onposition!).mockClear(); session.setPositionState.mockClear(); await player.seek(60); + flushSync(); expect(props.onposition).toHaveBeenCalledExactlyOnceWith(60); if (seekMode === "full") expect(session.setPositionState).toHaveBeenCalledOnce(); }, @@ -696,6 +740,7 @@ describe("Player component", () => { audio.dispatchEvent(new Event("timeupdate")); audio.dispatchEvent(new Event("waiting")); audio.dispatchEvent(new Event("canplay")); + flushSync(); expect(session.setActionHandler).not.toHaveBeenCalled(); navigation.set({ previous: false, next: false }); flushSync(); @@ -709,6 +754,7 @@ describe("Player component", () => { await player.play(item); player.unload(); await player.resume(); + flushSync(); expect(player.status).toBe("idle"); expect(player.position).toBe(0); expect(player.duration).toBe(0); diff --git a/tests/audio-transport.test.ts b/tests/audio-transport.test.ts new file mode 100644 index 0000000..bd0352e --- /dev/null +++ b/tests/audio-transport.test.ts @@ -0,0 +1,199 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it, vi } from "vitest"; +import { AudioTransport, type PlayerSource, type PlayerTrack } from "../src/audio-transport.svelte"; +import { AudioStub } from "./audio-test-helpers"; +import { deferred } from "./session-test-helpers"; + +const transports: AudioTransport[] = []; +afterEach(() => { + for (const transport of transports.splice(0)) transport.dispose(); + vi.unstubAllGlobals(); +}); +function setup() { + const audio = new AudioStub(); + const createAudio = vi.fn(function () { + return audio; + }); + vi.stubGlobal("Audio", createAudio); + const onstatechange = vi.fn(); + const onposition = vi.fn(); + const onended = vi.fn(); + const transport = new AudioTransport({ onstatechange, onposition, onended }); + transports.push(transport); + const release = vi.fn(); + const getSource = vi.fn( + async (_options: Parameters[0]): Promise => ({ + url: "blob:track", + seekMode: "full", + release, + }), + ); + const track: PlayerTrack = { metadata: { title: "Song", duration: 300 }, getSource }; + return { + transport, + audio, + createAudio, + track, + getSource, + release, + onstatechange, + onposition, + onended, + }; +} + +describe("AudioTransport without a mounted component", () => { + it("owns one native element and publishes synchronous states, progress, and completion", async () => { + const { transport, audio, createAudio, track, onstatechange, onposition, onended } = setup(); + await transport.play(track); + audio.currentTime = 15; + audio.dispatchEvent(new Event("timeupdate")); + expect(transport.position).toBe(15); + expect(onposition).toHaveBeenLastCalledWith(15); + audio.dispatchEvent(new Event("waiting")); + expect(transport.status).toBe("buffering"); + expect(transport.playing).toBe(true); + audio.dispatchEvent(new Event("canplay")); + transport.pause(); + await transport.resume(); + audio.dispatchEvent(new Event("ended")); + expect(onended).toHaveBeenCalledOnce(); + expect(onstatechange.mock.calls.map(([state]) => state)).toEqual([ + { status: "loading", playing: false }, + { status: "ready", playing: true }, + { status: "buffering", playing: true }, + { status: "ready", playing: true }, + { status: "ready", playing: false }, + { status: "ready", playing: true }, + { status: "ended", playing: false }, + ]); + await transport.resume(); + expect(transport.position).toBe(0); + expect(createAudio).toHaveBeenCalledOnce(); + }); + + it("pauses during acquisition and releases the late source exactly once", async () => { + const { transport, audio, track, getSource } = setup(); + const source = deferred(); + getSource.mockReturnValueOnce(source.promise); + const pending = transport.play(track); + const signal = getSource.mock.calls[0]![0]?.signal; + transport.pause(); + const release = vi.fn(); + source.resolve({ url: "blob:late", seekMode: "full", release }); + await pending; + expect(signal?.aborted).toBe(true); + expect(transport.playing).toBe(false); + expect(audio.play).not.toHaveBeenCalled(); + transport.dispose(); + expect(release).toHaveBeenCalledOnce(); + }); + + it("never lets a superseded result release the replacement", async () => { + const { transport, track, audio, getSource, release } = setup(); + const source = deferred(); + getSource.mockReturnValueOnce(source.promise); + const pending = transport.play(track); + await transport.play(track); + const obsoleteRelease = vi.fn(); + source.resolve({ url: "blob:old", seekMode: "full", release: obsoleteRelease }); + await pending; + expect(obsoleteRelease).toHaveBeenCalledOnce(); + expect(release).not.toHaveBeenCalled(); + expect(audio.src).toBe("blob:track"); + transport.dispose(); + expect(release).toHaveBeenCalledOnce(); + }); + + it("seeks offset streams in absolute seconds without losing pause intent", async () => { + const { transport, audio, track, getSource } = setup(); + getSource.mockResolvedValue({ + url: "blob:offset", + offset: 80, + seekMode: "buffered", + release() {}, + }); + await transport.play({ ...track, position: 85 }); + expect(audio.currentTime).toBe(5); + transport.pause(); + await transport.seek(90); + expect(audio.currentTime).toBe(10); + expect(transport.position).toBe(90); + expect(transport.playing).toBe(false); + audio.dispatchEvent(new Event("loadedmetadata")); + expect(transport.duration).toBe(300); + }); + + it("releases unsupported audio before transcoding, but does not transcode autoplay rejection", async () => { + const { transport, track, audio, getSource, release } = setup(); + const rawRelease = vi.fn(); + getSource.mockResolvedValueOnce({ url: "blob:raw", seekMode: "full", release: rawRelease }); + audio.play.mockRejectedValueOnce(new DOMException("Unsupported", "NotSupportedError")); + await transport.play(track); + expect(rawRelease).toHaveBeenCalledOnce(); + expect(getSource).toHaveBeenLastCalledWith(expect.objectContaining({ forceTranscode: true })); + expect(release).not.toHaveBeenCalled(); + const error = new DOMException("User activation required", "NotAllowedError"); + audio.play.mockRejectedValueOnce(error); + await transport.play(track); + expect(transport.error).toBe(error); + expect(transport.status).toBe("error"); + expect(getSource).toHaveBeenCalledTimes(3); + await transport.resume(); + expect(transport.playing).toBe(true); + expect(transport.error).toBeUndefined(); + }); + + it("disposes pending metadata work, native listeners, and commands idempotently", async () => { + const { transport, track, audio, getSource, release, onstatechange } = setup(); + audio.readyState = 0; + const remove = vi.spyOn(audio, "removeEventListener"); + const pending = transport.play({ ...track, position: 20 }); + await vi.waitFor(() => expect(audio.src).toBe("blob:track")); + transport.dispose(); + await pending; + expect(release).toHaveBeenCalledOnce(); + expect(remove).toHaveBeenCalledWith("loadedmetadata", expect.any(Function)); + expect(remove).toHaveBeenCalledWith("error", expect.any(Function)); + const calls = onstatechange.mock.calls.length; + for (const event of ["playing", "waiting", "ended", "loadedmetadata", "timeupdate", "error"]) + audio.dispatchEvent(new Event(event)); + transport.dispose(); + await transport.play(track); + await transport.resume(); + await transport.seek(50); + transport.pause(); + expect(onstatechange).toHaveBeenCalledTimes(calls); + expect(transport.status).toBe("idle"); + expect(audio.src).toBe(""); + expect(getSource).toHaveBeenCalledOnce(); + expect(release).toHaveBeenCalledOnce(); + }); + + it("does not restart if an idle notification disposes the transport during replacement", async () => { + const { transport, track, getSource, onstatechange } = setup(); + await transport.play(track); + onstatechange.mockImplementation((state) => { + if (state.status === "idle") transport.dispose(); + }); + await transport.play(track); + expect(transport.status).toBe("idle"); + expect(transport.metadata).toBeUndefined(); + expect(getSource).toHaveBeenCalledOnce(); + }); + + it("releases a source returned after disposal without publishing it", async () => { + const { transport, track, audio, getSource, onstatechange } = setup(); + const source = deferred(); + getSource.mockReturnValueOnce(source.promise); + const pending = transport.play(track); + transport.dispose(); + onstatechange.mockClear(); + const release = vi.fn(); + source.resolve({ url: "blob:late", seekMode: "full", release }); + await pending; + expect(release).toHaveBeenCalledOnce(); + expect(audio.play).not.toHaveBeenCalled(); + expect(onstatechange).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/media-session.test.ts b/tests/media-session.test.ts index 9b72011..b2d08dd 100644 --- a/tests/media-session.test.ts +++ b/tests/media-session.test.ts @@ -2,7 +2,8 @@ import { flushSync, mount, unmount } from "svelte"; import { SvelteMap } from "svelte/reactivity"; import { afterEach, describe, expect, it, vi } from "vitest"; -import Player, { type PlayerTrack } from "../src/audio-player.svelte"; +import Player from "../src/audio-player.svelte"; +import { AudioTransport, type PlayerTrack } from "../src/audio-transport.svelte"; const cleanups: (() => Promise)[] = []; function setup(unsupported = false, available = true) { @@ -59,9 +60,11 @@ function setup(unsupported = false, available = true) { ); const onnext = vi.fn(); const onprevious = vi.fn(); - const player = mount(Player, { + const player = new AudioTransport(); + const binding = mount(Player, { target: document.createElement("div"), props: { + transport: player, hasNext: true, hasPrevious: true, onnext, @@ -69,7 +72,10 @@ function setup(unsupported = false, available = true) { }, }); flushSync(); - const destroy = () => unmount(player); + const destroy = async () => { + player.dispose(); + await unmount(binding); + }; cleanups.push(destroy); const play = (metadata: PlayerTrack["metadata"], position = 0) => player.play({ @@ -222,6 +228,7 @@ describe("Player Media Session integration", () => { audio.playbackRate = 0; audio.dispatchEvent(new Event("loadedmetadata")); audio.dispatchEvent(new Event("timeupdate")); + flushSync(); expect(session.setPositionState).toHaveBeenLastCalledWith({ duration: 100, position: 100, diff --git a/tests/playback-page-test-app.svelte b/tests/playback-page-test-app.svelte index 91a65b4..cedc1ed 100644 --- a/tests/playback-page-test-app.svelte +++ b/tests/playback-page-test-app.svelte @@ -3,15 +3,28 @@ import Album from "../src/_album.svelte"; import Artist from "../src/_artist.svelte"; import AudioPlayer from "../src/audio-player.svelte"; + import { AudioTransport } from "../src/audio-transport.svelte"; import Player from "../src/ui/player.svelte"; let { props }: { props: Omit, "params" | "playbackState"> } = $props(); let albumId = $state("album"); let artistId = $state(); - let audio = $state>(); + let audio = $state.raw(); const loading = $derived(["loading", "buffering", "seeking"].includes(audio?.status ?? "idle")); - onMount(() => props.playback.attach(audio!)); + onMount(() => { + const transport = new AudioTransport({ + onposition: (position) => props.playback.setPosition(position), + onended: () => props.playback.ended(), + onstatechange: (state) => props.playback.updatePlayerState(state), + }); + audio = transport; + const detach = props.playback.attach(transport); + return () => { + detach(); + transport.dispose(); + }; + }); export function navigate(id?: string) { albumId = id; artistId = undefined; @@ -22,16 +35,15 @@ } - 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(); }); }); From 8c25f69ab5f00e5e40e92e12e6e44519128f3e9e Mon Sep 17 00:00:00 2001 From: Bogdan Chadkin Date: Sun, 15 Nov 2026 17:27:10 +0100 Subject: [PATCH 8/8] Initialize audio transport in component instance scope --- src/app.svelte | 47 ++++++++------------ tests/app-cache.test.ts | 97 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 29 deletions(-) diff --git a/src/app.svelte b/src/app.svelte index b4c2c69..fbf29cb 100644 --- a/src/app.svelte +++ b/src/app.svelte @@ -52,13 +52,17 @@ const covers = new Covers(selection); const playlists = new Playlists(selection); const trackEngine = new TrackEngine({ selection }); - let player = $state.raw(); const playback: Playback = new Playback({ selection, tracks: trackEngine, covers, isAvailable: (id) => !offlineMode || trackEngine.getStatus(id) === "downloaded", }); + const player = new AudioTransport({ + onposition: (position) => playback.setPosition(position), + onended: () => playback.ended(), + onstatechange: (state) => playback.updatePlayerState(state), + }); const session = untrack( () => new Session({ @@ -75,15 +79,9 @@ const offlineMode = $derived(session.offlineMode); const error = $derived(session.error); const refreshError = $derived(session.refreshError); - let playbackLoading = $derived( - ["loading", "buffering", "seeking"].includes(player?.status ?? "idle"), - ); + let playbackLoading = $derived(["loading", "buffering", "seeking"].includes(player.status)); let playbackError = $derived( - player?.error instanceof Error - ? player?.error.message - : player?.error - ? String(player?.error) - : "", + player.error instanceof Error ? player.error.message : player.error ? String(player.error) : "", ); let initialized = $state(false); let loading = $derived(!session.localReady); @@ -100,17 +98,10 @@ onMount(() => installLongPress()); onMount(() => installSwipeToDismiss()); onMount(() => { - const transport = new AudioTransport({ - onposition: (position) => playback.setPosition(position), - onended: () => playback.ended(), - onstatechange: (state) => playback.updatePlayerState(state), - }); - player = transport; - const detach = playback.attach(transport); + const detach = playback.attach(player); return () => { detach(); - transport.dispose(); - player = undefined; + player.dispose(); }; }); @@ -136,15 +127,13 @@ }); -{#if player} - = 0 && cache.queue.position > 0)} - hasNext={hasNextTrack} - onprevious={() => playback.previous()} - onnext={() => playback.next()} - /> -{/if} += 0 && cache.queue.position > 0)} + hasNext={hasNextTrack} + onprevious={() => playback.previous()} + onnext={() => playback.next()} +/> {#snippet settingsRoute()} @@ -177,7 +166,7 @@ {session} {playback} {appName} - playbackState={playbackLoading ? "loading" : player?.playing ? "playing" : "paused"} + playbackState={playbackLoading ? "loading" : player.playing ? "playing" : "paused"} /> {/snippet} @@ -190,7 +179,7 @@ {session} {playback} {appName} - playbackState={playbackLoading ? "loading" : player?.playing ? "playing" : "paused"} + playbackState={playbackLoading ? "loading" : player.playing ? "playing" : "paused"} /> {/snippet} diff --git a/tests/app-cache.test.ts b/tests/app-cache.test.ts index 561cc62..adaa8af 100644 --- a/tests/app-cache.test.ts +++ b/tests/app-cache.test.ts @@ -10,6 +10,10 @@ import { Cache, type LibrarySnapshot } from "../src/cache.svelte"; import { installDisk } from "./cache-test-helpers"; import { TrackEngine } from "../src/track.svelte"; import { Covers } from "../src/covers.svelte"; +import { AudioTransport } from "../src/audio-transport.svelte"; +import { Playback } from "../src/playback.svelte"; +import { Session } from "../src/session.svelte"; +import { AudioStub } from "./audio-test-helpers"; function mount(component: typeof App, { target }: { target: HTMLElement }) { return mountComponent(component, { @@ -71,6 +75,99 @@ afterEach(async () => { vi.unstubAllEnvs(); }); +it("owns an independent transport per App and detaches before disposing on unmount", async () => { + mocks.cache = new Cache(); + const audio: AudioStub[] = []; + vi.stubGlobal( + "Audio", + vi.fn(function () { + const element = new AudioStub(); + audio.push(element); + return element; + }), + ); + const mediaSession = { + metadata: null, + playbackState: "none", + setActionHandler: + vi.fn<(action: MediaSessionAction, handler: MediaSessionActionHandler | null) => void>(), + setPositionState: vi.fn(), + }; + vi.stubGlobal("navigator", { mediaSession }); + const events: string[] = []; + const transports: AudioTransport[] = []; + const attach = Playback.prototype.attach; + vi.spyOn(Playback.prototype, "attach").mockImplementation(function (this: Playback, player) { + const id = transports.push(player); + events.push(`attach ${id}`); + const detach = attach.call(this, player); + return () => { + events.push(`detach ${id}`); + detach(); + }; + }); + const start = Session.prototype.start; + vi.spyOn(Session.prototype, "start").mockImplementation(function (this: Session) { + events.push(`start ${transports.length}`); + return start.call(this); + }); + const dispose = AudioTransport.prototype.dispose; + vi.spyOn(AudioTransport.prototype, "dispose").mockImplementation(function (this: AudioTransport) { + events.push(`dispose ${transports.indexOf(this) + 1}`); + dispose.call(this); + }); + const create = () => { + const target = document.createElement("main"); + document.body.append(target); + const component = mount(App, { target }); + const cleanup = () => unmount(component); + cleanups.push(cleanup); + flushSync(); + return { target, cleanup }; + }; + const first = create(); + const second = create(); + expect(transports).toHaveLength(2); + expect(transports[0]).not.toBe(transports[1]); + expect(audio).toHaveLength(2); + expect(events).toEqual(["attach 1", "start 1", "attach 2", "start 2"]); + expect(mediaSession.playbackState).toBe("none"); + expect(mediaSession.setActionHandler).toHaveBeenCalledWith("play", expect.any(Function)); + + audio[0].src = "blob:test"; + audio[0].error = { code: 2, message: "Lifecycle playback error" }; + audio[0].dispatchEvent(new Event("error")); + flushSync(); + expect(first.target.textContent).toContain("Lifecycle playback error"); + expect(second.target.textContent).not.toContain("Lifecycle playback error"); + + await first.cleanup(); + cleanups.splice(cleanups.indexOf(first.cleanup), 1); + await second.cleanup(); + cleanups.splice(cleanups.indexOf(second.cleanup), 1); + const third = create(); + expect(transports[2]).not.toBe(transports[0]); + expect(audio).toHaveLength(3); + await third.cleanup(); + cleanups.splice(cleanups.indexOf(third.cleanup), 1); + expect(events).toEqual([ + "attach 1", + "start 1", + "attach 2", + "start 2", + "detach 1", + "dispose 1", + "detach 2", + "dispose 2", + "attach 3", + "start 3", + "detach 3", + "dispose 3", + ]); + const remainingHandlers = new Map(mediaSession.setActionHandler.mock.calls); + expect([...remainingHandlers.values()].every((handler) => handler === null)).toBe(true); +}); + function library(name: string, savedAt: number): LibrarySnapshot { return { artists: [{ id: "artist", name }],