From f946e42b65fd672a5f6444931f65aac075394c66 Mon Sep 17 00:00:00 2001 From: Bogdan Chadkin Date: Wed, 11 Nov 2026 13:40:37 +0100 Subject: [PATCH 1/4] Add server-backed favourites and filtered Search --- CONTRIBUTING.md | 24 +- src/_album.svelte | 44 ++- src/_artist.svelte | 38 +- src/_library.svelte | 21 +- src/_settings.svelte | 2 +- src/app.svelte | 7 +- src/cache.svelte.ts | 68 +++- src/favourites.svelte.ts | 166 +++++++++ src/icon.svelte | 1 + src/network.svelte.ts | 63 +++- src/schema.ts | 21 ++ src/session.svelte.ts | 51 ++- src/sprite.svg | 1 + src/subsonic-client.ts | 41 ++- src/ui/favourite-button.svelte | 135 +++++++ src/ui/player.svelte | 70 +++- tests/browser/favourites-lifecycle.test.cjs | 274 ++++++++++++++ tests/browser/favourites.test.cjs | 369 +++++++++++++++++++ tests/cache-favourites.test.ts | 60 +++ tests/favourites-legacy.test.ts | 75 ++++ tests/favourites.test.ts | 192 ++++++++++ tests/fixtures/legacy-synthetic-library.json | 25 ++ tests/network-factory.test.ts | 3 + tests/network-favourites.test.ts | 131 +++++++ tests/network-library.test.ts | 36 +- tests/search-favourites.test.ts | 114 ++++++ tests/session-favourites.test.ts | 302 +++++++++++++++ tests/session-test-helpers.ts | 7 +- tests/subsonic-client.test.ts | 29 +- website/deezer-client.ts | 10 + website/demo.test.ts | 2 +- 31 files changed, 2322 insertions(+), 60 deletions(-) create mode 100644 src/favourites.svelte.ts create mode 100644 src/ui/favourite-button.svelte create mode 100644 tests/browser/favourites-lifecycle.test.cjs create mode 100644 tests/browser/favourites.test.cjs create mode 100644 tests/cache-favourites.test.ts create mode 100644 tests/favourites-legacy.test.ts create mode 100644 tests/favourites.test.ts create mode 100644 tests/fixtures/legacy-synthetic-library.json create mode 100644 tests/network-favourites.test.ts create mode 100644 tests/search-favourites.test.ts create mode 100644 tests/session-favourites.test.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 39d4554..059d55a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,6 +40,7 @@ The workspace contains the root app (`src/`, `tests/`) and `@libras/website` (`w | `AudioPlayer` | Audio transport, seeking, keyboard shortcuts, and Media Session | | `Covers` / `TrackEngine` | Resource acquisition, download scheduling, and browser URL lifetimes | | `Playlists` | Server-confirmed playlist operations and conflict detection; no offline outbox | +| `Favourites` | Serialized server-confirmed stars and reconciliation; independent account checkpoint, no outbox | | `Router` | Query routes, native fragment anchors, active navigation metadata, and optional view transitions | Routes use the bare query, for example `/webapp/?/library/artist/123#section`. Encode each dynamic path segment with `encodeURIComponent`; fragments remain native in-page anchors. The service worker serves one cached app shell for root/index navigation requests, including their route queries; assets and API requests are excluded. @@ -47,6 +48,7 @@ Routes use the bare query, for example `/webapp/?/library/artist/123#section`. E ### Persistence and account safety - Read Cache collections directly; change them through explicit methods. Session owns account details; Cache accepts an opaque account key and hashes it for storage. An undefined key creates an empty, non-persisting fallback. A defined key does not mean hydration succeeded. +- Favourites use an independent `favourites.json` checkpoint. Server confirmation publishes before device checkpointing; cache failures never repeat a server write. Unreadable favourites documents are preserved, even after a server refresh restores visible memory, and are excluded from drainable retirement writes. Downloaded-only filtering does not disconnect authenticated favourites access. An unknown write outcome blocks further edits until an authoritative refresh succeeds. - Library, queue, playlist, and image memory updates checkpoint asynchronously. Downloads instead await explicit queued/failed/completed commits in one versioned store; failed jobs require explicit Retry or a bulk Download action. Interrupted queued jobs restart from scratch, never adopting unregistered bytes. Successful byte close wins cancellation while completed metadata commits; cancellation joins that work. Unknown queued/failed job fields, including old attempts, are ignored on load and omitted on subsequent writes; orphan-file reclamation after old attempts or abrupt termination is intentionally out of scope. Offline library limits browsing/listening, not requested downloads. Do not treat visible state as proof of persistence. Unreadable download documents are preserved, not reset; readable saved files remain usable. - Credentials use localStorage only, until disconnect. Token login stores username/token/salt; verified direct-password fallback stores the actual password. localStorage is not encrypted and is readable by same-origin scripts. Never log credentials or credential-bearing URLs. Legacy token records migrate without changing account keys; migration writeback is best-effort. - Disconnect retains local data for offline use. Same-account reconnects reuse the live cache to preserve edits. Account changes drain old writes and retire resources before committing the new workspace. Late results must not leak into a different account. @@ -94,17 +96,17 @@ NODE_PATH=/path/to/external/node_modules PREVIEW_URL=http://127.0.0.1:5173 \ Select suites for the behavior being changed: -| Suite in `tests/browser/` | Coverage | -| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `edgerunner.test.cjs` | Shared styles, fonts, native controls, overlays, and reduced motion | -| `navigation.test.cjs` | Document scrolling, shell, playback, query routes, anchors, and optional offline navigation | -| `startup.test.cjs` | Initial Settings route, reloads, and subsequent animated navigation | -| `pwa-updates.test.cjs` | Self-hosted production builds: real worker installation, per-tab consent, repeated discovery, offline application, failed precache, and optional old-plugin migration | -| `library.test.cjs`, `search.test.cjs` | Browsing, actions, responsive layouts, and native dismissal | -| `downloads.test.cjs`, `settings.test.cjs` | Actual app/OPFS behavior with intercepted Subsonic requests | -| `atmosphere.test.cjs` | Document/dialog scroll timelines; self-contained, no server required | -| `website-cascade.test.cjs` | Script-free landing layout, keyboard/FAQ behavior, and standalone demo journeys | -| `design-improvements.test.cjs` | Compact details, full-height player, queue anchors, confirmation, gradients, popover timing, titles, and demo guidance (website server) | +| Suite in `tests/browser/` | Coverage | +| ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `edgerunner.test.cjs` | Shared styles, fonts, native controls, overlays, and reduced motion | +| `navigation.test.cjs` | Document scrolling, shell, playback, query routes, anchors, and optional offline navigation | +| `startup.test.cjs` | Initial Settings route, reloads, and subsequent animated navigation | +| `pwa-updates.test.cjs` | Self-hosted production builds: real worker installation, per-tab consent, repeated discovery, offline application, failed precache, and optional old-plugin migration | +| `library.test.cjs`, `search.test.cjs`, `favourites.test.cjs` | Browsing, actions, responsive layouts, native dismissal, server stars, and Search-entry drafts | +| `downloads.test.cjs`, `settings.test.cjs` | Actual app/OPFS behavior with intercepted Subsonic requests | +| `atmosphere.test.cjs` | Document/dialog scroll timelines; self-contained, no server required | +| `website-cascade.test.cjs` | Script-free landing layout, keyboard/FAQ behavior, and standalone demo journeys | +| `design-improvements.test.cjs` | Compact details, full-height player, queue anchors, confirmation, gradients, popover timing, titles, and demo guidance (website server) | `cache-downloads.test.cjs` exercises native OPFS close/publication boundaries and restart-from-scratch behavior by importing the owning modules. Run it against the app **dev** server; Downloads, Settings, and navigation checks can run against production preview. diff --git a/src/_album.svelte b/src/_album.svelte index c0cfdb3..3140a57 100644 --- a/src/_album.svelte +++ b/src/_album.svelte @@ -1,5 +1,6 @@ {album?.title ?? "Album"} | {appName} @@ -276,8 +296,14 @@
- -

{menuTrack?.title ?? album?.title}

+ +

+ {menuTrackId !== undefined ? menuTrack?.title : album?.title} +

+
{/snippet} diff --git a/src/_artist.svelte b/src/_artist.svelte index 28c6347..fe24410 100644 --- a/src/_artist.svelte +++ b/src/_artist.svelte @@ -1,5 +1,6 @@ {artist?.name ?? "Artist"} | {appName} @@ -308,6 +330,14 @@ Download + {/snippet} diff --git a/src/_library.svelte b/src/_library.svelte index 297f8ad..63584f5 100644 --- a/src/_library.svelte +++ b/src/_library.svelte @@ -1,5 +1,6 @@ Your library | {appName} @@ -278,6 +293,10 @@ Download + {/snippet} diff --git a/src/_settings.svelte b/src/_settings.svelte index 81f7032..299d1e5 100644 --- a/src/_settings.svelte +++ b/src/_settings.svelte @@ -327,7 +327,7 @@ aria-label={session.refreshing ? "Refreshing…" : "Refresh library"} aria-disabled={session.syncing} aria-busy={session.refreshing} - disabled={session.offlineMode || session.busy} + disabled={session.busy || session.syncing} onclick={() => { if (!session.syncing) void session.refresh(); }} diff --git a/src/app.svelte b/src/app.svelte index 941e678..5962d9b 100644 --- a/src/app.svelte +++ b/src/app.svelte @@ -1,6 +1,7 @@ + +{#if favourites && target} + + {#if reason || error} +

+ {error || reason} + { + dismiss(); + // Now Playing contains its Actions popover inside a modal dialog. + overlay?.parentElement?.closest("dialog")?.close(); + }}>Open settings +

+ {/if} +{/if} + + diff --git a/src/ui/player.svelte b/src/ui/player.svelte index a8aa7cd..a9c480a 100644 --- a/src/ui/player.svelte +++ b/src/ui/player.svelte @@ -1,5 +1,6 @@ -{#if favourites && target} +{#if target} -{#if visible}{/if} +{#if visible} false, + key: () => "", + pending: new Map(), + targetError: () => "", + } as unknown as import("../src/favourites.svelte").Favourites)} + />{/if} diff --git a/tests/search.test.ts b/tests/search.test.ts index af9401b..8f52540 100644 --- a/tests/search.test.ts +++ b/tests/search.test.ts @@ -15,7 +15,7 @@ describe("shareable search URLs", () => { 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(parseSearch(url.searchParams)).toEqual({ query, types, favourite: false }); expect(url.pathname).toBe("/demo/"); expect(url.hash).toBe(""); } @@ -27,7 +27,7 @@ describe("shareable search URLs", () => { ); const entries = [...parameters]; const criteria = parseSearch(parameters); - expect(criteria).toEqual({ query: "first", types: ["artist", "track"] }); + expect(criteria).toEqual({ query: "first", types: ["artist", "track"], favourite: false }); expect([...parameters]).toEqual(entries); expect(searchHref(criteria.query, criteria.types)).toBe( "?/search&type=artist&type=track&q=first", @@ -36,17 +36,19 @@ describe("shareable search URLs", () => { expect(parseSearch(new URLSearchParams("/search&type=unknown"))).toEqual({ query: "", types: [], + favourite: false, }); expect(parseSearch(new URLSearchParams("/search&q=&q=second"))).toEqual({ query: "", types: [], + favourite: false, }); 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: [] }); + expect(parseSearch(url.searchParams)).toEqual({ query: "", types: [], favourite: false }); }); }); diff --git a/tests/session-favourites.test.ts b/tests/session-favourites.test.ts index 2c3cf4b..fb64933 100644 --- a/tests/session-favourites.test.ts +++ b/tests/session-favourites.test.ts @@ -119,97 +119,112 @@ it.each([false, true])( }, ); -it("preserves a submitted uncertain write through disconnect and failed same-account reconnect with real Cache", async () => { - installDisk(); - const library = { - savedAt: 100, - lastModified: 100, - artists: [{ id: "artist", name: "Artist", localOnly: false }], - albums: [{ id: "album", title: "Album", artistIds: ["artist"], genres: [] }], - tracks: [{ id: "song", title: "Song", albumId: "album", artistIds: ["artist"], genres: [] }], - }; - const seed = new Cache(getAccountKey(credentials)); - await seed.load(); - await seed.replaceLibrary(library); - seed.setFavourites({ fetchedAt: 1, artists: [], albums: [], tracks: [] }); - await seed.flush(); - const submitted = deferred(); - const response = deferred(); - let remoteStarred = false; - let failReads = false; - let writes = 0; - vi.stubGlobal( - "fetch", - vi.fn(async (url: string) => { - if (url.includes("star.view")) { - writes++; - remoteStarred = true; - submitted.resolve(); - // Model a server-accepted write whose response outlives client cancellation. - await response.promise; - } - if (url.includes("getStarred2") && failReads) throw new Error("Mock transport unavailable"); - return new Response( - JSON.stringify({ - "subsonic-response": { - status: "ok", - indexes: { lastModified: 100 }, - starred2: { song: remoteStarred ? [{ id: "song", title: "Song" }] : [] }, - }, - }), - ); - }), - ); - const storage = createStorage(); - storage.setItem("navidrome-offline-mode", "true"); - const s = createSession(true, storage, true); - s.loadCache.mockRestore(); - s.saveLibrary.mockRestore(); - s.metadata.readLibrary.mockResolvedValue(library); - try { - s.session.start(); - await vi.waitFor(() => expect(s.session.localReady).toBe(true)); - await vi.waitFor(() => expect(s.session.syncing).toBe(false)); - const cache = s.selection.cache!; - expect(cache.tracks.has("song")).toBe(true); - const edit = s.favourites!.toggle({ kind: "tracks", id: "song" }); - const retiredEdit = edit.catch((error) => error); - await submitted.promise; - s.session.disconnect(); - expect(s.favourites!.outcomeUnknown).toBe(true); - failReads = true; - expect( - await s.session.connect({ - host: credentials.host, - username: credentials.username, - password: "fixture", +it.each(["normal", "credentials", "preferences"])( + "preserves a submitted uncertain write through %s disconnect and failed same-account reconnect with real Cache", + async (failure) => { + installDisk(); + const library = { + savedAt: 100, + lastModified: 100, + artists: [{ id: "artist", name: "Artist", localOnly: false }], + albums: [{ id: "album", title: "Album", artistIds: ["artist"], genres: [] }], + tracks: [{ id: "song", title: "Song", albumId: "album", artistIds: ["artist"], genres: [] }], + }; + const seed = new Cache(getAccountKey(credentials)); + await seed.load(); + await seed.replaceLibrary(library); + seed.setFavourites({ fetchedAt: 1, artists: [], albums: [], tracks: [] }); + await seed.flush(); + const submitted = deferred(); + const response = deferred(); + let remoteStarred = false; + let failReads = false; + let writes = 0; + vi.stubGlobal( + "fetch", + vi.fn(async (url: string) => { + if (url.includes("star.view")) { + writes++; + remoteStarred = true; + submitted.resolve(); + // Model a server-accepted write whose response outlives client cancellation. + await response.promise; + } + if (url.includes("getStarred2") && failReads) throw new Error("Mock transport unavailable"); + return new Response( + JSON.stringify({ + "subsonic-response": { + status: "ok", + indexes: { lastModified: 100 }, + starred2: { song: remoteStarred ? [{ id: "song", title: "Song" }] : [] }, + }, + }), + ); }), - ).toBe(true); - await vi.waitFor(() => expect(s.session.syncing).toBe(false)); - expect(s.selection.cache).toBe(cache); - expect(s.favourites!.error).toBeDefined(); - expect(s.favourites!.has({ kind: "tracks", id: "song" })).toBe(false); - await expect(s.favourites!.toggle({ kind: "tracks", id: "song" })).rejects.toThrow( - "Outcome unknown", ); - response.resolve(); - expect(await retiredEdit).toMatchObject({ name: "AbortError" }); - expect(s.favourites!.outcomeUnknown).toBe(true); - expect(writes).toBe(1); - failReads = false; - await s.session.refresh(); - expect(s.favourites!.has({ kind: "tracks", id: "song" })).toBe(true); - expect(s.favourites!.outcomeUnknown).toBe(false); - expect(writes).toBe(1); - await cache.flush(); - const restored = new Cache(getAccountKey(credentials)); - await restored.load(); - expect(restored.favourites.tracks[0]?.id).toBe("song"); - } finally { - response.resolve(); - await s.destroy(); - } -}); + const storage = createStorage(); + storage.setItem("navidrome-offline-mode", "true"); + const s = createSession(true, storage, true); + s.loadCache.mockRestore(); + s.saveLibrary.mockRestore(); + s.metadata.readLibrary.mockResolvedValue(library); + try { + s.session.start(); + await vi.waitFor(() => expect(s.session.localReady).toBe(true)); + await vi.waitFor(() => expect(s.session.syncing).toBe(false)); + const cache = s.selection.cache!; + expect(cache.tracks.has("song")).toBe(true); + const edit = s.favourites!.toggle({ kind: "tracks", id: "song" }); + const retiredEdit = edit.catch((error) => error); + await submitted.promise; + const failingStorage = + failure === "credentials" + ? vi.spyOn(s.auth, "clear").mockImplementation(() => { + throw new Error("Storage denied"); + }) + : failure === "preferences" + ? vi.spyOn(storage, "setItem").mockImplementation(() => { + throw new Error("Storage denied"); + }) + : undefined; + expect(s.session.disconnect()).toBe(failure === "normal"); + expect(s.favourites!.available).toBe(false); + failingStorage?.mockRestore(); + expect(s.favourites!.outcomeUnknown).toBe(true); + failReads = true; + expect( + await s.session.connect({ + host: credentials.host, + username: credentials.username, + password: "fixture", + }), + ).toBe(true); + await vi.waitFor(() => expect(s.session.syncing).toBe(false)); + expect(s.selection.cache).toBe(cache); + expect(s.favourites!.error).toBeDefined(); + expect(s.favourites!.has({ kind: "tracks", id: "song" })).toBe(false); + await expect(s.favourites!.toggle({ kind: "tracks", id: "song" })).rejects.toThrow( + "Outcome unknown", + ); + response.resolve(); + expect(await retiredEdit).toMatchObject({ name: "AbortError" }); + expect(s.favourites!.outcomeUnknown).toBe(true); + expect(writes).toBe(1); + failReads = false; + await s.session.refresh(); + expect(s.favourites!.has({ kind: "tracks", id: "song" })).toBe(true); + expect(s.favourites!.outcomeUnknown).toBe(false); + expect(writes).toBe(1); + await cache.flush(); + const restored = new Cache(getAccountKey(credentials)); + await restored.load(); + expect(restored.favourites.tracks[0]?.id).toBe("song"); + } finally { + response.resolve(); + await s.destroy(); + } + }, +); it("retires an account with preserved corrupt favourites after a confirmed server refresh", async () => { const disk = installDisk(); From d249ecd966834f23772716240c7b480e17fbf771 Mon Sep 17 00:00:00 2001 From: Bogdan Chadkin Date: Mon, 16 Nov 2026 18:37:41 +0100 Subject: [PATCH 4/4] Simplify favourite controls and remove scripted focus restoration --- src/_album.svelte | 15 +- src/_artist.svelte | 15 +- src/_library.svelte | 12 +- src/_search.svelte | 38 ++--- src/ui/favourite-button.svelte | 180 +++++++++----------- src/ui/player.svelte | 108 ++++-------- tests/browser/favourites-lifecycle.test.cjs | 23 ++- tests/browser/favourites.test.cjs | 157 ++++++++++++++--- tests/favourite-button.test.ts | 101 +++++++++++ tests/search-favourites.test.ts | 21 +-- tests/search-filters.test.ts | 37 ++++ 11 files changed, 424 insertions(+), 283 deletions(-) create mode 100644 tests/favourite-button.test.ts diff --git a/src/_album.svelte b/src/_album.svelte index 713f8a7..5820810 100644 --- a/src/_album.svelte +++ b/src/_album.svelte @@ -39,8 +39,6 @@ appName = "Libras", }: Props = $props(); - let section = $state(); - let heading = $state(); const offlineMode = $derived(session.offlineMode); const loading = $derived(!session.localReady); const libraryAvailable = $derived(cache.savedAt !== undefined); @@ -98,26 +96,20 @@ const wasOpen = sheet?.open || popover?.matches(":popover-open"); if (wasOpen) dismissActions(); menuTrackId = undefined; - if (!wasOpen) return; - const fallback = heading ?? section; - if (fallback?.checkVisibility()) { - fallback.tabIndex = -1; - fallback.focus({ preventScroll: true }); - } }); {album?.title ?? "Album"} | {appName} -
+
{#if libraryAvailable && artist && album}
-

{album.title}

+

{album.title}

{album.displayArtist ?? artist.name} @@ -385,8 +377,7 @@ (); - let heading = $state(); const loading = $derived(!session.localReady); const offlineMode = $derived(session.offlineMode); const libraryAvailable = $derived(cache.savedAt !== undefined); @@ -99,19 +97,13 @@ const wasOpen = sheet?.open || popover?.matches(":popover-open"); if (wasOpen) dismissActions(); menuAlbumId = undefined; - if (!wasOpen) return; - const fallback = heading ?? section; - if (fallback?.checkVisibility()) { - fallback.tabIndex = -1; - fallback.focus({ preventScroll: true }); - } }); {artist?.name ?? "Artist"} | {appName} -
+
{#if libraryAvailable && artist}
-

{artist.name}

+

{artist.name}

diff --git a/src/_search.svelte b/src/_search.svelte index 4013d6a..5b14fb1 100644 --- a/src/_search.svelte +++ b/src/_search.svelte @@ -109,12 +109,6 @@ album: albums.get(track.albumId)?.title ?? "", })), }; - const membership = Object.fromEntries( - searchGroups.map((group) => [ - group, - new Set(favourites?.[kindFor[group]].map((item) => item.id)), - ]), - ) as Record>; if (!available && favourites) { for (const group of searchGroups) { const ids = new Set(records[group].map((item) => item.id)); @@ -132,13 +126,13 @@ } } const groupIndex = (group: SearchGroup) => { - const prepare = (records: SearchRecord[]) => ({ - records, - snapshot: fuzzysort.snapshot(records, { keys: ["title", "artist", "album"] }), - }); + const membership = favourites && new Set(favourites[kindFor[group]].map((item) => item.id)); + const candidates = membership + ? records[group].filter((record) => membership.has(record.id)) + : records[group]; return { - ordinary: prepare(records[group].filter((record) => !record.unavailable)), - favourite: prepare(records[group].filter((record) => membership[group].has(record.id))), + records: candidates, + snapshot: fuzzysort.snapshot(candidates, { keys: ["title", "artist", "album"] }), }; }; return { @@ -156,11 +150,10 @@ index: ReturnType, query: string, browse = false, - favourite = false, ) { query = query.trim().replace(/\s+/g, " "); const groups = searchGroups.map((group) => { - const { records, snapshot } = index[group][favourite ? "favourite" : "ordinary"]; + const { records, snapshot } = index[group]; // Retrieve matches explicitly without a library limit so equal scores can be // ordered deterministically before applying the UI limit. const matches = query @@ -200,7 +193,6 @@ import type { Session } from "./session.svelte"; import type { Playback } from "./playback.svelte"; - let searchInput = $state(); let { favourites, cache, @@ -219,23 +211,22 @@ appName?: string; } = $props(); + const parameters = $derived(getSearchParameters()); + const criteria = $derived(parseSearch(parameters)); + const favouriteMode = $derived(criteria.favourite); const index = $derived( createSearchIndex( cache.artists, cache.albums, cache.tracks, session.offlineMode ? isAvailable : undefined, - cache.favourites, + favouriteMode ? cache.favourites : undefined, ), ); - const parameters = $derived(getSearchParameters()); - const criteria = $derived(parseSearch(parameters)); const selectedTypes = $derived(criteria.types); const singleType = $derived(selectedTypes.length === 1); - const matches = $derived( - searchLibrary(index, criteria.query, singleType || criteria.favourite, criteria.favourite), - ); + const matches = $derived(searchLibrary(index, criteria.query, singleType || favouriteMode)); // 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; @@ -337,7 +328,6 @@ // Consume the disappeared selection, even if its overlay was already dismissed. // Later background index changes must not steal the user's new focus. menuSelection = undefined; - if (wasOpen) searchInput?.focus({ preventScroll: true }); } }); @@ -394,7 +384,6 @@
diff --git a/src/ui/favourite-button.svelte b/src/ui/favourite-button.svelte index 3ea2baa..1f6f373 100644 --- a/src/ui/favourite-button.svelte +++ b/src/ui/favourite-button.svelte @@ -1,5 +1,5 @@ -{#if target} +{#if target || icon} - {#if reason || error} -

- {error || reason} - { - dismiss(); - onsettings?.(); - }}>Open settings +

-

+ {error || reason || progress} +

+ {#if reason || error} + { + if (onsettings) onsettings(); + else { + event.currentTarget.closest("[popover]")?.hidePopover(); + event.currentTarget.closest("dialog")?.close(); + } + }}>Open settings + {/if} +
{/if} {/if} diff --git a/tests/browser/favourites-lifecycle.test.cjs b/tests/browser/favourites-lifecycle.test.cjs index c1fa52f..f4bc06a 100644 --- a/tests/browser/favourites-lifecycle.test.cjs +++ b/tests/browser/favourites-lifecycle.test.cjs @@ -202,17 +202,14 @@ test("disappeared Library/detail rows close without retargeting; dismissed Searc await page.locator(panel).waitFor({ state: "hidden" }); if (dismissed) { assert.equal(await safeFocus.evaluate((node) => node === document.activeElement), true); - } else if (scenario.heading) { - assert.notEqual(await page.evaluate(() => window.closedRowTitle), scenario.heading); - await page.waitForFunction( - (heading) => - document.activeElement?.matches("h1") && - document.activeElement.textContent === heading, - scenario.heading, - ); } else { - await page.waitForFunction( - () => document.activeElement?.getAttribute("aria-labelledby") === "library-heading", + if (scenario.heading) + assert.notEqual(await page.evaluate(() => window.closedRowTitle), scenario.heading); + assert.equal( + await page.evaluate( + () => !!document.activeElement?.matches('h1, section[tabindex="-1"]'), + ), + false, ); } assert.deepEqual(writes, []); @@ -318,8 +315,10 @@ test("disappeared Library/detail rows close without retargeting; dismissed Searc await navigate("/search&type=track"); await page.getByRole("button", { name: /^(Play|Toggle playback for) Keep song$/ }).click(); await page.getByRole("button", { name: "Open Now Playing", exact: true }).click(); - await open("Actions for Keep song", "#playing-actions"); - await recover("#playing-actions"); + const player = page.locator("#player-dialog"); + await player.getByRole("button", { name: "Favourite current track", exact: true }).click(); + await player.getByText(/Fixture permission denied/).waitFor(); + await player.getByRole("link", { name: "Open settings", exact: true }).click(); await page.locator("#player-dialog").waitFor({ state: "hidden" }); } assert.deepEqual(errors, []); diff --git a/tests/browser/favourites.test.cjs b/tests/browser/favourites.test.cjs index 59fa92e..559d3b8 100644 --- a/tests/browser/favourites.test.cjs +++ b/tests/browser/favourites.test.cjs @@ -16,7 +16,7 @@ test("favourites actions, confirmation, overlay lifetimes, unavailable results a page.on("pageerror", (e) => errors.push(e.message)); const artist = { id: "same", name: "Fixture artist" }; const album = { id: "same", name: "Fixture album", artists: [artist] }; - const songs = Array.from({ length: 14 }, (_, i) => ({ + const songs = Array.from({ length: 70 }, (_, i) => ({ id: i ? `song-${i}` : "same", title: `Fixture track ${String(i).padStart(2, "0")}`, artists: [artist], @@ -94,7 +94,10 @@ test("favourites actions, confirmation, overlay lifetimes, unavailable results a async function shot(name) { if (evidence) { await mkdir(evidence, { recursive: true }); - await page.screenshot({ path: `${evidence}/${name}.png`, fullPage: true }); + await page.screenshot({ + path: `${evidence}/${name}.png`, + fullPage: !name.startsWith("player-"), + }); } } async function searchShots(state) { @@ -118,12 +121,23 @@ test("favourites actions, confirmation, overlay lifetimes, unavailable results a } async function toggle(name, panel, expected) { const overlay = await open(name, panel); - await overlay.getByRole("button", { name: /^(Add to|Remove from) favourites$/ }).click(); - await overlay.waitFor({ state: "hidden" }); + await overlay.getByRole("button", { name: /^(Add to|Remove from) favourites$/ }).focus(); + await page.keyboard.press("Enter"); + if (expected[2] === "missing") await overlay.waitFor({ state: "hidden" }); + else { + await overlay + .getByRole("button", { + name: expected[0] === "star" ? "Remove from favourites" : "Add to favourites", + exact: true, + }) + .waitFor(); + assert.equal(await overlay.isVisible(), true); + await shot("menu-success-in-place"); + await overlay.getByRole("button", { name: /^(Add to|Remove from) favourites$/ }).focus(); + await shot("menu-keyboard"); + await page.keyboard.press("Escape"); + } assert.deepEqual(writes.at(-1), expected); - const invoker = page.getByRole("button", { name, exact: true }).filter({ visible: true }); - if (await invoker.count()) - assert.equal(await invoker.evaluate((node) => node === document.activeElement), true); } try { await page.goto(base); @@ -155,14 +169,49 @@ test("favourites actions, confirmation, overlay lifetimes, unavailable results a "song", "same", ]); + await navigate("/search&q=Fixture"); + await page.getByRole("button", { name: "Show more tracks" }).click(); + const trackRows = page + .getByRole("region", { name: "Tracks", exact: true }) + .locator(".track-row"); + assert.equal(await trackRows.count(), 13); + await toggle("Open menu for Fixture track 01", "#search-menu-popover", [ + "star", + "song", + "song-1", + ]); + assert.equal(await trackRows.count(), 13); + await toggle("Open menu for Fixture track 01", "#search-menu-popover", [ + "unstar", + "song", + "song-1", + ]); + assert.equal(await trackRows.count(), 13); await navigate("/search&type=track"); const input = page.getByRole("searchbox"); await input.waitFor(); assert.equal(await input.inputValue(), ""); assert.equal( await page.getByRole("region", { name: "Tracks", exact: true }).locator(".track-row").count(), - 14, + 48, + ); + await page.locator(".library-sentinel").scrollIntoViewIfNeeded(); + await page.waitForFunction( + () => document.querySelectorAll('section[aria-label="Tracks"] .track-row').length === 70, ); + await toggle("Open menu for Fixture track 01", "#search-menu-popover", [ + "star", + "song", + "song-1", + ]); + assert.equal(await trackRows.count(), 70); + await toggle("Open menu for Fixture track 01", "#search-menu-popover", [ + "unstar", + "song", + "song-1", + ]); + assert.equal(await trackRows.count(), 70); + await input.scrollIntoViewIfNeeded(); await searchShots("inactive"); const historyLength = await page.evaluate(() => history.length); await input.fill("Fixture"); @@ -225,7 +274,6 @@ test("favourites actions, confirmation, overlay lifetimes, unavailable results a "missing", ]); await unavailable.waitFor({ state: "hidden" }); - await page.waitForFunction(() => document.activeElement?.id === "library-search"); await navigate("/search&type=track"); reject = true; let overlay = await open("Open menu for Fixture track 00", "#search-menu-popover"); @@ -258,22 +306,68 @@ test("favourites actions, confirmation, overlay lifetimes, unavailable results a await page.keyboard.press("Escape"); await page.getByRole("button", { name: "Play Fixture track 00", exact: true }).click(); await page.getByRole("button", { name: "Open Now Playing" }).click(); - overlay = await open("Actions for Fixture track 00", "#playing-actions"); - await shot("favourites-now-playing-1280"); - await overlay.getByRole("button", { name: "Add to favourites", exact: true }).click(); - await overlay.waitFor({ state: "hidden" }); - assert.deepEqual(writes.at(-1), ["star", "song", "same"]); - assert.equal( - await page - .getByRole("button", { name: "Actions for Fixture track 00", exact: true }) - .evaluate((node) => node === document.activeElement), - true, + const player = page.locator("#player-dialog"); + const favourite = player.getByRole("button", { name: "Favourite current track", exact: true }); + async function playerShots(state) { + for (const width of [1280, 390]) { + await page.setViewportSize({ width, height: 900 }); + const bounds = await player.locator('[aria-label="Playback controls"]').boundingBox(); + const controls = await player.locator(".player-controls").boundingBox(); + assert.ok(Math.abs(bounds.x + bounds.width / 2 - controls.x - controls.width / 2) < 1); + const button = await favourite.boundingBox(); + assert.ok(button.width >= 44 && button.height >= 44); + await shot(`player-${state}-${width}`); + } + await page.setViewportSize({ width: 1280, height: 900 }); + } + assert.equal(await favourite.getAttribute("aria-pressed"), "false"); + await playerShots("unselected"); + gate = new Promise((resolve) => { + release = resolve; + }); + await favourite.click(); + await player.getByText("Adding to favourites…", { exact: true }).waitFor(); + assert.equal(await favourite.isDisabled(), true); + assert.equal(await favourite.getAttribute("aria-pressed"), "false"); + await playerShots("pending"); + await player.getByRole("button", { name: "Next", exact: true }).click(); + await player.getByRole("heading", { name: "Fixture track 01", exact: true }).waitFor(); + assert.equal(await favourite.isEnabled(), true); + reject = true; + release(); + gate = undefined; + await page.waitForTimeout(150); + assert.equal(await player.getByText(/Fixture permission denied/).count(), 0); + assert.equal(await favourite.getAttribute("aria-pressed"), "false"); + await player.getByRole("button", { name: "Previous", exact: true }).click(); + await player.getByText(/Fixture permission denied/).waitFor(); + reject = false; + await favourite.click(); + await page.waitForFunction( + () => + document + .querySelector('#player-dialog [aria-label="Favourite current track"]') + .getAttribute("aria-pressed") === "true", ); + assert.deepEqual(writes.at(-1), ["star", "song", "same"]); + await playerShots("selected"); reject = true; - overlay = await open("Actions for Fixture track 00", "#playing-actions"); - await overlay.getByRole("button", { name: "Remove from favourites", exact: true }).click(); - await overlay.getByText(/Fixture permission denied/).waitFor(); - await overlay.getByRole("link", { name: "Open settings", exact: true }).click(); + await favourite.click(); + await player.getByText(/Fixture permission denied/).waitFor(); + await playerShots("failure"); + await page.setViewportSize({ width: 320, height: 900 }); + await page.evaluate(() => (document.documentElement.style.fontSize = "200%")); + await shot("player-feedback-enlarged"); + assert.equal(await player.evaluate((node) => node.scrollWidth <= node.clientWidth), true); + await page.evaluate(() => (document.documentElement.style.fontSize = "")); + await page.setViewportSize({ width: 1280, height: 900 }); + reject = false; + readsFail = true; + await favourite.click(); + await player.getByText(/Outcome unknown/).waitFor(); + assert.equal(await favourite.getAttribute("aria-pressed"), "true"); + await playerShots("unknown"); + await player.getByRole("link", { name: "Open settings", exact: true }).click(); await page.locator("#player-dialog").waitFor({ state: "hidden" }); await page.getByRole("heading", { name: "Settings", exact: true }).waitFor(); reject = false; @@ -365,8 +459,7 @@ test("favourites actions, confirmation, overlay lifetimes, unavailable results a await page.getByRole("heading", { name: "No favourites yet." }).waitFor(); await shot("favourites-confirmed-empty-1280"); await searchShots("empty"); - // A resize can hide the captured desktop invoker without dismissing its popover. - // Success must then use this Search owner's input, not a global page selector. + // Async completion never dismisses the menu or pulls focus back to it. await navigate("/search&type=track"); overlay = await open("Open menu for Fixture track 02", "#search-menu-popover"); gate = new Promise((resolve) => { @@ -376,22 +469,32 @@ test("favourites actions, confirmation, overlay lifetimes, unavailable results a await overlay.getByRole("button", { name: "Adding to favourites…", exact: true }).waitFor(); await page.setViewportSize({ width: 390, height: 900 }); assert.equal(await overlay.isVisible(), true); + await input.focus(); release(); gate = undefined; - await overlay.waitFor({ state: "hidden" }); - await page.waitForFunction(() => document.activeElement?.id === "library-search"); + await overlay.getByRole("button", { name: "Remove from favourites", exact: true }).waitFor(); + assert.equal(await overlay.isVisible(), true); + assert.equal(await input.evaluate((node) => node === document.activeElement), true); + await page.keyboard.press("Escape"); await page.setViewportSize({ width: 1280, height: 900 }); await navigate("/search"); await input.fill("literal URL query"); await navigate("/library"); await navigate("/search"); assert.equal(await input.inputValue(), ""); // A fresh bare URL has no hidden draft. + await navigate("/search&type=track"); + await page.getByRole("button", { name: "Play Fixture track 02", exact: true }).click(); await navigate("/settings"); await page.getByRole("button", { name: "Disconnect", exact: true }).click(); await page .locator("#disconnect-dialog") .getByRole("button", { name: "Disconnect", exact: true }) .click(); + await page.getByRole("button", { name: "Open Now Playing" }).click(); + await player.getByText(/Reconnect in Settings/).waitFor(); + await playerShots("reconnect"); + await player.getByRole("link", { name: "Open settings", exact: true }).click(); + await player.waitFor({ state: "hidden" }); await navigate("/library/album/same"); overlay = await open("Actions for Fixture album", "#album-detail-menu-popover"); assert.equal( diff --git a/tests/favourite-button.test.ts b/tests/favourite-button.test.ts new file mode 100644 index 0000000..7fb424c --- /dev/null +++ b/tests/favourite-button.test.ts @@ -0,0 +1,101 @@ +// @vitest-environment happy-dom +import { flushSync, mount, unmount } from "svelte"; +import { SvelteMap } from "svelte/reactivity"; +import { expect, it, vi } from "vitest"; +import FavouriteButton from "../src/ui/favourite-button.svelte"; +import type { Favourites } from "../src/favourites.svelte"; +import type { Cache } from "../src/cache.svelte"; + +it("keeps mutation failures local to the captured engine, cache and target without focus effects", async () => { + let reject!: (error: Error) => void; + const toggle = vi.fn( + () => + new Promise((_, fail) => { + reject = fail; + }), + ); + const engine = { + available: true, + outcomeUnknown: false, + pending: new SvelteMap(), + key: (target: { id: string }) => target.id, + has: () => false, + targetError: () => "", + toggle, + } as unknown as Favourites; + const firstCache = {} as Cache; + const nextCache = {} as Cache; + const state = new SvelteMap([ + ["engine", engine], + ["cache", firstCache], + ["id", "A"], + ]); + const target = document.createElement("div"); + document.body.append(target); + const input = document.createElement("input"); + target.append(input); + const app = mount(FavouriteButton, { + target, + props: { + get favourites() { + return state.get("engine") as Favourites; + }, + get cache() { + return state.get("cache") as Cache; + }, + get target() { + const id = state.get("id") as string | undefined; + return id === undefined ? undefined : { kind: "tracks" as const, id }; + }, + icon: true, + }, + }); + flushSync(); + try { + target.querySelector("button")!.click(); + expect(toggle).toHaveBeenCalledWith({ kind: "tracks", id: "A" }); + state.set("id", "B"); + flushSync(); + input.focus(); + reject(new Error("A rejected")); + await Promise.resolve(); + flushSync(); + expect(target.textContent).not.toContain("A rejected"); + expect(document.activeElement).toBe(input); + expect(target.querySelector("button")!.disabled).toBe(false); + state.set("id", "A"); + flushSync(); + await vi.waitFor(() => { + flushSync(); + expect(target.textContent).toContain("A rejected"); + }); + state.set("cache", nextCache); + flushSync(); + expect(target.textContent).not.toContain("A rejected"); + state.set("cache", firstCache); + state.set("engine", { ...engine }); + flushSync(); + expect(target.textContent).not.toContain("A rejected"); + state.set("engine", engine); + flushSync(); + target.querySelector("button")!.click(); + reject(new DOMException("Retired", "AbortError")); + await new Promise((resolve) => setTimeout(resolve, 0)); + flushSync(); + expect(target.textContent).not.toContain("A rejected"); + expect(target.textContent).not.toContain("Retired"); + engine.pending.set("A", false); + flushSync(); + expect(target.querySelector("button")!.disabled).toBe(true); + expect(target.textContent).toContain("Removing from favourites…"); + target.querySelector("button")!.click(); + expect(toggle).toHaveBeenCalledTimes(2); + state.delete("id"); + flushSync(); + expect(target.querySelector("button")!.disabled).toBe(true); + expect(target.querySelector(".favourite-feedback")).toBeNull(); + } finally { + await unmount(app); + target.remove(); + } +}); diff --git a/tests/search-favourites.test.ts b/tests/search-favourites.test.ts index 133b1b0..7cf8897 100644 --- a/tests/search-favourites.test.ts +++ b/tests/search-favourites.test.ts @@ -20,8 +20,9 @@ const favourites: FavouriteState = { tracks: [{ id: "missing", title: "Saved song", artist: "Saved credit" }], }; const index = createSearchIndex(artists, albums, tracks, undefined, favourites); +const ordinary = createSearchIndex(artists, albums, tracks); const search = (query = "", favourite = true) => - searchLibrary(index, query, true, favourite).groups; + searchLibrary(favourite ? index : ordinary, query, true).groups; describe("URL favourites modifier", () => { it("accepts only 1, omits false and canonicalizes types without interpreting text", () => { @@ -55,9 +56,7 @@ describe("URL favourites modifier", () => { expect(search()[2].records[0].href).toBeUndefined(); expect(search("Saved", false)[2].total).toBe(0); const empty = createSearchIndex(new Map(), new Map(), new Map(), undefined, favourites); - expect(searchLibrary(empty, "", true, true).groups.map((group) => group.total)).toEqual([ - 1, 0, 1, - ]); + expect(searchLibrary(empty, "", true).groups.map((group) => group.total)).toEqual([1, 0, 1]); }); it("ANDs downloaded eligibility and preserves credited contributors", () => { const downloaded = createSearchIndex(artists, albums, tracks, (id) => id === "a", { @@ -65,14 +64,18 @@ describe("URL favourites modifier", () => { artists: [{ id: "guest", title: "Guest" }], }); expect( - searchLibrary(downloaded, "", true).groups[0].records.map((record) => record.id), + searchLibrary( + createSearchIndex(artists, albums, tracks, (id) => id === "a"), + "", + true, + ).groups[0].records.map((record) => record.id), ).toEqual(["same", "guest"]); expect( - searchLibrary(downloaded, "", true, true).groups.map((group) => + searchLibrary(downloaded, "", true).groups.map((group) => group.records.map((record) => record.id), ), ).toEqual([["guest"], [], []]); - expect(searchLibrary(downloaded, "Bravo").groups[2].total).toBe(1); + expect(searchLibrary(downloaded, "Bravo").groups[2].total).toBe(0); }); it("reacts to confirmed removal without falling back to ordinary results", () => { const next = createSearchIndex(artists, albums, tracks, undefined, { @@ -81,9 +84,7 @@ describe("URL favourites modifier", () => { albums: [], tracks: [], }); - expect(searchLibrary(next, "", true, true).groups.every((group) => group.total === 0)).toBe( - true, - ); + expect(searchLibrary(next, "", true).groups.every((group) => group.total === 0)).toBe(true); expect(favourites.artists).toHaveLength(1); expect(search()[0].total).toBe(1); }); diff --git a/tests/search-filters.test.ts b/tests/search-filters.test.ts index 87e2129..1653cac 100644 --- a/tests/search-filters.test.ts +++ b/tests/search-filters.test.ts @@ -1,5 +1,6 @@ // @vitest-environment happy-dom import { flushSync, mount, unmount } from "svelte"; +import fuzzysort from "fuzzysort"; import { afterEach, describe, expect, it, vi } from "vitest"; import type Search from "../src/_search.svelte"; import Harness from "./search-test-app.svelte"; @@ -67,6 +68,42 @@ describe("independent search filters", () => { target.remove(); } }); + it("builds only the active index and does not rebuild snapshots for text edits", async () => { + const props = fixture(3); + const membership = vi.fn(() => ({ fetchedAt: 1, artists: [], albums: [], tracks: [] })); + Object.defineProperty(props.cache, "favourites", { get: membership }); + const snapshot = vi.spyOn(fuzzysort, "snapshot"); + const target = document.createElement("main"); + document.body.append(target); + const app = mount(Harness, { target, props: { props } }); + flushSync(); + try { + expect(membership).not.toHaveBeenCalled(); + expect(snapshot).toHaveBeenCalledTimes(3); + const input = target.querySelector("input")!; + for (const query of ["Fixture", "Fixture track", "Fixture track 2"]) { + input.value = query; + input.dispatchEvent(new Event("input", { bubbles: true })); + flushSync(); + } + expect(snapshot).toHaveBeenCalledTimes(3); + expect(membership).not.toHaveBeenCalled(); + [...target.querySelectorAll("button")] + .find((button) => button.textContent?.trim() === "Favourites")! + .click(); + flushSync(); + expect(snapshot).toHaveBeenCalledTimes(6); + expect(membership).toHaveBeenCalled(); + input.value = "different"; + input.dispatchEvent(new Event("input", { bubbles: true })); + flushSync(); + expect(snapshot).toHaveBeenCalledTimes(6); + } finally { + snapshot.mockRestore(); + await unmount(app); + target.remove(); + } + }); it.each(Array.from({ length: 8 }, (_, mask) => mask))( "intersects favourites with type combination %s and text", async (mask) => {