Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 77 additions & 61 deletions src/_search.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -411,73 +418,82 @@
<p class="body">Try another search or change the selected types.</p>
</div>
{:else}
{#each results as { group, records, total }}
{#each results as { group, records, total, batches } (group)}
{#if total > 0}
<section class="stack-lg" aria-label={group}>
<header class="row-md row-justify">
<h2 class="heading-lg uppercase">{group}</h2>
<span class="metadata text-subtle">{total}</span>
</header>
<div class="stack-sm">
{#each records as record (record.id)}
{@const track = group === "Tracks" ? cache.tracks.get(record.id) : undefined}
{#each batches as batch, batchIndex (batchIndex)}
<!-- The first batch is visible; only trailing, below-fold batches defer rendering. -->
<div
class="menu-item track-row"
aria-current={track && currentTrackId === track.id ? "true" : undefined}
class="stack-sm"
class:track-group={batchIndex > 0}
style:--track-group-rows={batch.length}
>
<div class="row-sm">
<Artwork {covers} id={record.artworkId} size="sm" />
<div>
<p class="label">{record.title}</p>
<p class="caption text-secondary">{supportingText(group, record)}</p>
</div>
</div>
{#if record.href}
<a
class="button-quiet link-target"
href={record.href}
aria-label={record.title}
data-longpressfor="search-menu"
data-longpress="show-modal"
onfocus={() => selectMenu(group, record.id)}
></a>
{:else}
<button
class="button-quiet link-target"
aria-label={currentTrackId === record.id
? `Toggle playback for ${record.title}`
: `Play ${record.title}`}
data-longpressfor="search-menu"
data-longpress="show-modal"
onfocus={() => selectMenu(group, record.id)}
onclick={() => playback.toggleTrack(record.id, trackContext(record.id))}
></button>
{/if}
<div class="row-sm">
{#if track?.duration !== undefined}
<span class="metadata text-subtle">{formatDuration(track.duration)}</span>
{/if}
<button
class="button only-mobile"
data-variant="secondary"
commandfor="search-menu"
command="show-modal"
aria-label={`Open menu for ${record.title}`}
onclick={() => selectMenu(group, record.id)}
{#each batch as record (record.id)}
{@const track = group === "Tracks" ? cache.tracks.get(record.id) : undefined}
<div
class="menu-item track-row"
aria-current={track && currentTrackId === track.id ? "true" : undefined}
>
<Icon name="menu" />
</button>
<button
class="button only-desktop"
data-variant="secondary"
commandfor="search-menu-popover"
command="toggle-popover"
aria-label={`Open menu for ${record.title}`}
onclick={() => selectMenu(group, record.id)}
>
<Icon name="menu" />
</button>
</div>
<div class="row-sm">
<Artwork {covers} id={record.artworkId} size="sm" />
<div>
<p class="label">{record.title}</p>
<p class="caption text-secondary">{supportingText(group, record)}</p>
</div>
</div>
{#if record.href}
<a
class="button-quiet link-target"
href={record.href}
aria-label={record.title}
data-longpressfor="search-menu"
data-longpress="show-modal"
onfocus={() => selectMenu(group, record.id)}
></a>
{:else}
<button
class="button-quiet link-target"
aria-label={currentTrackId === record.id
? `Toggle playback for ${record.title}`
: `Play ${record.title}`}
data-longpressfor="search-menu"
data-longpress="show-modal"
onfocus={() => selectMenu(group, record.id)}
onclick={() => playback.toggleTrack(record.id, trackContext(record.id))}
></button>
{/if}
<div class="row-sm">
{#if track?.duration !== undefined}
<span class="metadata text-subtle">{formatDuration(track.duration)}</span>
{/if}
<button
class="button only-mobile"
data-variant="secondary"
commandfor="search-menu"
command="show-modal"
aria-label={`Open menu for ${record.title}`}
onclick={() => selectMenu(group, record.id)}
>
<Icon name="menu" />
</button>
<button
class="button only-desktop"
data-variant="secondary"
commandfor="search-menu-popover"
command="toggle-popover"
aria-label={`Open menu for ${record.title}`}
onclick={() => selectMenu(group, record.id)}
>
<Icon name="menu" />
</button>
</div>
</div>
{/each}
</div>
{/each}
</div>
Expand Down
81 changes: 79 additions & 2 deletions tests/browser/search.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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";
});
Expand Down
77 changes: 64 additions & 13 deletions tests/search-filters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLButtonElement>("[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(
Expand All @@ -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<HTMLButtonElement>('[aria-label="Show more tracks"]')!.click();
flushSync();
expect(section.querySelector(".track-row")).toBe(first);
expect(first.parentElement).toBe(firstBatch);
target.querySelectorAll<HTMLButtonElement>("[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);
Expand Down
Loading