From 0f6b0c7fd7cf49bcabe5507162fbb89a7d175e80 Mon Sep 17 00:00:00 2001 From: Bogdan Chadkin Date: Mon, 16 Nov 2026 16:58:48 +0100 Subject: [PATCH] Preserve search groups and defer offscreen result rendering --- src/_search.svelte | 138 +++++++++++++++++++--------------- tests/browser/search.test.cjs | 81 +++++++++++++++++++- tests/search-filters.test.ts | 77 +++++++++++++++---- 3 files changed, 220 insertions(+), 76 deletions(-) diff --git a/src/_search.svelte b/src/_search.svelte index 097d40c..5f16f45 100644 --- a/src/_search.svelte +++ b/src/_search.svelte @@ -211,13 +211,20 @@ (cache.reportingError ? "Some local data could not be restored or saved." : ""), ); + const resultGroupSize = 40; const results = $derived( matches.groups .filter((_, i) => !selectedTypes.length || selectedTypes.includes(searchTypes[i])) - .map((result) => ({ - ...result, - records: result.records.slice(0, singleType ? limit : limits[result.group]), - })), + .map((result) => { + const records = result.records.slice(0, singleType ? limit : limits[result.group]); + return { + ...result, + records, + batches: Array.from({ length: Math.ceil(records.length / resultGroupSize) }, (_, index) => + records.slice(index * resultGroupSize, (index + 1) * resultGroupSize), + ), + }; + }), ); function isAvailable(id: string) { @@ -411,7 +418,7 @@

Try another search or change the selected types.

{:else} - {#each results as { group, records, total }} + {#each results as { group, records, total, batches } (group)} {#if total > 0}
@@ -419,65 +426,74 @@
- {#each records as record (record.id)} - {@const track = group === "Tracks" ? cache.tracks.get(record.id) : undefined} + {#each batches as batch, batchIndex (batchIndex)} + + {/each}
{/each} diff --git a/tests/browser/search.test.cjs b/tests/browser/search.test.cjs index de3f928..814f3c0 100644 --- a/tests/browser/search.test.cjs +++ b/tests/browser/search.test.cjs @@ -35,15 +35,24 @@ test("Search filters, incremental lists, URLs and native actions", async () => { })); 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é 東京" : ""}`, + title: `Search fixture track ${i}${i % 40 === 0 ? " — a long title with naturally wrapped lines and Unicode Beyoncé 東京" : ""}`, albumId: album.id, artists: [artist], duration: 123, - contentType: "audio/mpeg", + contentType: "audio/wav", })); + // PCM WAV header + one minute of silent mono 8kHz/16-bit audio. + const audio = Buffer.concat([ + Buffer.from("UklGRiSmDgBXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YQCmDgA=", "base64"), + Buffer.alloc(8000 * 2 * 60), + ]); await page.route("https://search.example.test/**", async (route) => { const url = new URL(route.request().url()); const method = url.pathname.split("/").pop().replace(".view", ""); + if (method === "stream") { + await route.fulfill({ contentType: "audio/wav", body: audio }); + return; + } let fields = {}; if (method === "ping") fields = { version: "1.16.1", type: "test", serverVersion: "1", openSubsonic: true }; @@ -97,6 +106,27 @@ test("Search filters, incremental lists, URLs and native actions", async () => { assert.equal(await tracks.locator(".track-row").count(), 48); assert.equal(await tracks.locator("header .metadata").textContent(), "120"); assert.equal(await page.getByRole("button", { name: "Show more tracks" }).count(), 0); + assert.equal( + await tracks + .locator(".track-row") + .first() + .evaluate((node) => getComputedStyle(node.parentElement).contentVisibility), + "visible", + ); + const deferred = await tracks + .locator(".track-group") + .first() + .evaluate((node) => ({ + visibility: getComputedStyle(node).contentVisibility, + intrinsic: getComputedStyle(node).containIntrinsicBlockSize, + belowViewport: node.getBoundingClientRect().top > innerHeight, + rows: node.style.getPropertyValue("--track-group-rows"), + })); + assert.equal(deferred.visibility, "auto"); + assert.notEqual(deferred.intrinsic, "none"); + assert.ok(deferred.intrinsic.includes("auto")); + assert.equal(deferred.belowViewport, true); + assert.equal(deferred.rows, "8"); // Native menu behavior and utility-only layout at desktop and narrow widths. const options = tracks @@ -161,6 +191,53 @@ test("Search filters, incremental lists, URLs and native actions", async () => { assert.equal(await first.evaluate((node) => node.isConnected), true); } assert.equal(await tracks.locator(".library-sentinel").count(), 0); + await tracks.locator(".track-row").last().scrollIntoViewIfNeeded(); + await tracks.locator(".track-row").first().scrollIntoViewIfNeeded(); + // Sequential Tab crosses from the uncontained first batch into the next batch. + await tracks + .locator(".track-row") + .nth(39) + .getByRole("button", { name: /^Open menu/ }) + .filter({ visible: true }) + .focus(); + await page.keyboard.press("Tab"); + const boundary = tracks.locator(".track-row").nth(40); + assert.equal( + await boundary.locator(".link-target").evaluate((node) => node === document.activeElement), + true, + ); + await page.keyboard.press("Enter"); + await tracks.locator('.track-row[aria-current="true"]').waitFor(); + assert.equal(await boundary.getAttribute("aria-current"), "true"); + await page + .getByRole("contentinfo", { name: "Music player", exact: true }) + .locator('button[aria-label="Pause"][aria-busy="false"]') + .waitFor(); + await page.setViewportSize({ width: 320, height: 900 }); + const boundaryMenu = boundary + .getByRole("button", { name: /^Open menu/ }) + .filter({ visible: true }); + await boundaryMenu.click(); + await sheet.waitFor({ state: "visible" }); + assert.equal(await sheet.getByRole("heading").textContent(), songs[40].title); + if (screenshots) await page.screenshot({ path: `${screenshots}/search-contained-menu.png` }); + await page.keyboard.press("Escape"); + assert.equal(await boundaryMenu.evaluate((node) => node === document.activeElement), true); + const geometry = await tracks.locator(".track-row").evaluateAll((nodes) => + [39, 40, 41].map((index) => { + const bounds = nodes[index].getBoundingClientRect(); + return { top: bounds.top, bottom: bounds.bottom, height: bounds.height }; + }), + ); + assert.ok(geometry[1].height > 100); + assert.ok(geometry[1].top >= geometry[0].bottom); + assert.ok(geometry[2].top >= geometry[1].bottom); + assert.equal( + await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), + true, + ); + if (screenshots) await page.screenshot({ path: `${screenshots}/search-contained-narrow.png` }); + await page.setViewportSize({ width: 1280, height: 900 }); await page.evaluate(() => { location.hash = "search-anchor"; }); diff --git a/tests/search-filters.test.ts b/tests/search-filters.test.ts index 85b2d8a..b426d70 100644 --- a/tests/search-filters.test.ts +++ b/tests/search-filters.test.ts @@ -43,6 +43,30 @@ function fixture(count = 120) { } describe("independent search filters", () => { + it("preserves a retained group's section and first row when restricting types", async () => { + const target = document.createElement("main"); + document.body.append(target); + const app = mount(Harness, { target, props: { props: fixture(3) } }); + flushSync(); + try { + const input = target.querySelector("input")!; + input.value = "Fixture"; + input.dispatchEvent(new Event("input", { bubbles: true })); + flushSync(); + expect(target.querySelectorAll("section[aria-label]")).toHaveLength(3); + const section = target.querySelector('section[aria-label="Tracks"]')!; + const firstRow = section.querySelector(".track-row"); + expect(firstRow).not.toBeNull(); + target.querySelectorAll("[aria-pressed]")[2].click(); + flushSync(); + expect(target.querySelectorAll("section[aria-label]")).toHaveLength(1); + expect(target.querySelector('section[aria-label="Tracks"]')).toBe(section); + expect(section.querySelector(".track-row")).toBe(firstRow); + } finally { + await unmount(app); + target.remove(); + } + }); it("appends batches, retains rows across hash changes and resets on new criteria", async () => { let callback: IntersectionObserverCallback; vi.stubGlobal( @@ -61,27 +85,54 @@ describe("independent search filters", () => { const app = mount(Harness, { target, props: { props: fixture(120) } }); flushSync(); try { + const input = target.querySelector("input")!; + input.value = "Fixture"; + input.dispatchEvent(new Event("input", { bubbles: true })); + flushSync(); + const section = target.querySelector('section[aria-label="Tracks"]')!; + const first = section.querySelector(".track-row")!; + const firstBatch = first.parentElement!; + target.querySelector('[aria-label="Show more tracks"]')!.click(); + flushSync(); + expect(section.querySelector(".track-row")).toBe(first); + expect(first.parentElement).toBe(firstBatch); 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(); + const container = firstBatch.parentElement!; + let previous = [...container.children]; + for (const [size, rowCounts] of [ + [48, [40, 8]], + [96, [40, 40, 16]], + [120, [40, 40, 40]], + ] as const) { + if (size > 48) { + 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(section.querySelector(".track-row")).toBe(first); + expect(first.parentElement).toBe(firstBatch); + const wrappers = [...container.children] as HTMLElement[]; + expect(wrappers.map((batch) => batch.childElementCount)).toEqual(rowCounts); + wrappers.forEach((batch, index) => { + expect(batch.style.getPropertyValue("--track-group-rows")).toBe( + String(batch.childElementCount), + ); + expect(batch.classList.contains("track-group")).toBe(index > 0); + }); + previous.forEach((batch, index) => expect(wrappers[index]).toBe(batch)); + previous = wrappers; } expect(target.querySelector(".library-sentinel")).toBeNull(); expect(target.textContent).toContain("119"); - window.navigation.navigate("?/search&type=track#anchor", { history: "push" }); + window.navigation.navigate("?/search&type=track&q=Fixture#anchor", { history: "push" }); flushSync(); expect(target.querySelectorAll(".track-row")).toHaveLength(120); - const input = target.querySelector("input")!; - input.value = "Fixture"; + input.value = "Fixture track"; input.dispatchEvent(new Event("input", { bubbles: true })); flushSync(); expect(target.querySelectorAll(".track-row")).toHaveLength(48);