import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { cleanup, fireEvent, render, waitFor } from "@solidjs/testing-library"; import { captureArtifact, expectNoDiagnostics } from "../test/diagnostics"; import App from "../App"; import { clearConnection, saveConnection } from "../lib/connection"; import { library } from "../lib/harvest"; import { albumCells } from "../lib/library/grid"; import { player } from "../lib/player"; import { buildRows } from "../lib/library/rows"; import { forgetLandedCovers } from "../lib/library/covers"; import { mediaFiles, navidromeFetch, type FakeMediaFile } from "../test/navidrome"; import { stubResizeObserver } from "../test/env"; /** * The two views over one index: the list and the album grid. The grid is the * interesting case because it must never unmount the list — clicking a cover * scrolls the *list* to that album, which only works if the list was alive and * scrollable the whole time. */ const artists = ["Aphex Twin", "Autechre", "Boards of Canada", "Carpenter Brut"]; const shelves: [artist: string, album: string, albumId: string][] = artists.flatMap((artist, a) => [0, 1, 2].map( (n) => [artist, `${artist} record ${n}`, `al-${a}-${n}`] as [string, string, string], ), ); const songs: FakeMediaFile[] = shelves.flatMap(([albumArtist, album, albumId], i) => mediaFiles({ album, albumArtist, albumId }, 3, i), ); const panes = () => [...document.querySelectorAll(".lib-pane")]; const listPane = () => panes()[0]!; const gridPane = () => panes()[1]!; const albumTitles = (pane: Element) => [...pane.querySelectorAll(".lib-scroll .lib-row--album .lib-section-name--album")].map( (n) => n.textContent, ); const gridScroller = () => gridPane().querySelector(".album-scroll")!; const isInactive = (el: HTMLElement) => el.classList.contains("lib-pane--inactive"); async function bootConnected() { vi.stubGlobal("fetch", navidromeFetch(songs)); saveConnection({ host: "https://nav.example.com", username: "admin", password: "wordpass" }); render(() => ); await waitFor(() => expect(library().status()).toBe("ready"), { timeout: 3000 }); await waitFor(() => expect(document.querySelectorAll(".lib-row--track").length).toBeGreaterThan(0), ); } beforeEach(() => { localStorage.clear(); clearConnection(); library().reset(); // The landed-cover ledger is per page, and a test is a page. Leaked from the // grid's own tests it would let a cell here draw a cover it never asked for. forgetLandedCovers(); // wide enough for the grid to lay out real columns (5 × 170 + gaps), short // enough that the list's windowed rows are genuinely absent below the fold stubResizeObserver({ width: 1000, height: 0 }); }); afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); it("leaves the tracks painted behind the gallery, and only that way round", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); fireEvent.keyDown(window, { key: "g" }); await waitFor(() => expect(gridPane().querySelectorAll(".album-cell").length).toBe(12)); // The gallery has no background of its own — the panes are transparent — so // the thing that used to stand between a cover and its tracks was the list // pane being `visibility: hidden`. `--behind` is what un-hides it: the rows // are the same library the covers are made of, and seeing them is what makes // this one screen rather than two. expect(listPane().classList.contains("lib-pane--behind")).toBe(true); // …as scenery, not as a second set of rows to click: inert is what keeps them // out of the a11y tree and off the click path now that visibility is not. expect(listPane().hasAttribute("inert")).toBe(true); // The other direction stays hidden. 1,703 sleeves painting behind a list // nobody is looking through is paint for nothing. fireEvent.keyDown(window, { key: "Escape" }); await waitFor(() => expect(gridPane().classList.contains("lib-pane--inactive")).toBe(true)); expect(gridPane().classList.contains("lib-pane--behind")).toBe(false); expect(listPane().hasAttribute("inert")).toBe(false); }); expectNoDiagnostics(artifact); }); it("switches to the grid without unmounting the song list", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); // 4 artists × 3 albums × 3 tracks: enough rows that the 900px scroll buffer // still leaves the tail of the library below the fold const tracksBefore = document.querySelectorAll(".lib-row--track").length; expect(tracksBefore).toBeGreaterThan(0); fireEvent.keyDown(window, { key: "g" }); // open the grid // 5 columns, and the 3-row lead buffer covers all 12 album cells await waitFor(() => expect(gridPane().querySelectorAll(".album-cell").length).toBe(12)); // the list is merely inactive: still mounted, rows and scroll position kept, // which is exactly what click-to-reveal depends on expect(isInactive(listPane())).toBe(true); expect(isInactive(gridPane())).toBe(false); expect(document.querySelectorAll(".lib-row--track").length).toBe(tracksBefore); const img = gridPane().querySelector(".album-img")!; expect(img.getAttribute("src")).toContain("/rest/getCoverArt"); // The album row's cover is inherited from the first track carrying one // (`rows.ts` aggregates `coverArt` off its songs), and on the native API a track // is identified to getCoverArt by its own id — there is no artwork id on that // row (`CoverArtID` is a method, `model/mediafile.go:135-142`), and the artwork // endpoint resolves an entity id to that entity's cover. expect(img.getAttribute("src")).toContain("id=al-0-0-s0"); // Asked for at the tile's own size, because jsdom reports a 1× screen: the // flat 2× this used to send asked the server to resample four times the // pixels the display could show. `covers.test.ts` pins the HiDPI case. expect(img.getAttribute("src")).toContain("size=160"); }); expectNoDiagnostics(artifact); }); it("shows something on every tile while covers are in flight", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); fireEvent.keyDown(window, { key: "g" }); // open the grid await waitFor(() => expect(gridPane().querySelectorAll(".album-cell").length).toBe(12)); // jsdom never fires img.onload, so every cell here is stuck in "loading" — // the exact state that made the grid look like it appeared a second late. // The tile must carry its own content under the art, not wait for it. const arts = [...gridPane().querySelectorAll(".album-art")]; expect(arts).toHaveLength(12); for (const art of arts) { expect(art.getAttribute("data-loaded")).toBe("false"); const img = art.querySelector("img"); const ph = art.querySelector(".album-art-ph"); expect(img).toBeTruthy(); expect(ph).toBeTruthy(); // under the image, not instead of it expect(ph!.textContent).toMatch(/^[A-Z0-9]{2}$/); } // and the captions give each cell its final shape immediately expect(gridPane().querySelector(".album-name")!.textContent).toBe("Aphex Twin record 0"); }); expectNoDiagnostics(artifact); }); it("clicking a cover brings that album into view in the song list", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const target = albumCells(buildRows(library().songs())).at(-1)!; // far below the fold, so "in view" after the click cannot be an accident: // its album section row is not in the DOM at all yet expect(albumTitles(listPane())).not.toContain(target.name); fireEvent.keyDown(window, { key: "g" }); // open the grid await waitFor(() => expect(gridPane().querySelectorAll(".album-cell").length).toBe(12)); // scroll the grid until the target cell itself exists, then click it const scroller = gridScroller(); scroller.scrollTop = 208; fireEvent.scroll(scroller); const cell = await waitFor(() => { const found = [...gridPane().querySelectorAll(".album-cell")].find((c) => c.textContent?.includes(target.name), ); expect(found).toBeTruthy(); return found!; }); fireEvent.click(cell); await waitFor(() => expect(isInactive(listPane())).toBe(false)); expect(isInactive(gridPane())).toBe(true); // the album row aligned to the top, with one row of context above it const list = listPane().querySelector(".lib-scroll")!; await waitFor(() => expect(list.scrollTop).toBe((target.rowIndex - 1) * 30)); await waitFor(() => expect(albumTitles(listPane())).toContain(target.name)); }); expectNoDiagnostics(artifact); }); it("re-applies the reveal when the pane refuses the first scrollTop write", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const target = albumCells(buildRows(library().songs())).at(-1)!; fireEvent.keyDown(window, { key: "g" }); // open the grid await waitFor(() => expect(gridPane().querySelectorAll(".album-cell").length).toBe(12)); const cell = [...gridPane().querySelectorAll(".album-cell")].find((c) => c.textContent?.includes(target.name), )!; // The browser failure this stands in for: a pane that has only just become // visible can refuse a scrollTop write, and jsdom never refuses anything. // Swallow the first write, accept the rest — the reveal must still land. const list = listPane().querySelector(".lib-scroll")!; let writes = 0; let accepted = 0; Object.defineProperty(list, "scrollTop", { configurable: true, get: () => accepted, set: (v: number) => { writes += 1; if (writes > 1) accepted = v; }, }); fireEvent.click(cell); await waitFor(() => expect(list.scrollTop).toBe((target.rowIndex - 1) * 30)); expect(writes).toBeGreaterThan(1); // it took the retry, not the first write await waitFor(() => expect(albumTitles(listPane())).toContain(target.name)); }); expectNoDiagnostics(artifact); }); it("highlights the revealed album's section — header and its tracks — after a cover click", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const target = albumCells(buildRows(library().songs())).at(-1)!; fireEvent.keyDown(window, { key: "g" }); // open the grid await waitFor(() => expect(gridPane().querySelectorAll(".album-cell").length).toBe(12)); const cell = [...gridPane().querySelectorAll(".album-cell")].find((c) => c.textContent?.includes(target.name), )!; fireEvent.click(cell); await waitFor(() => expect(albumTitles(listPane())).toContain(target.name)); const albumRow = [ ...listPane().querySelectorAll(".lib-scroll .lib-row--album"), ].find((n) => n.textContent?.includes(target.name))!; expect(albumRow.classList.contains("lib-row--hl")).toBe(true); expect(albumRow.classList.contains("lib-row--hl-top")).toBe(true); // its three tracks share the wash — and only its three; the section below // must stay un-highlighted await waitFor(() => expect(listPane().querySelectorAll(".lib-scroll .lib-row--track.lib-row--hl").length).toBe(3), ); const hlRows = [...listPane().querySelectorAll(".lib-scroll .lib-row--hl")]; expect(hlRows.at(-1)!.classList.contains("lib-row--hl-bottom")).toBe(true); expect(hlRows.filter((r) => r.classList.contains("lib-row--album")).length).toBe(1); }); expectNoDiagnostics(artifact); }); it("clicking an album row holds the highlight on that section", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const name = albumTitles(listPane())[1]!; // visible in the initial window const row = [...listPane().querySelectorAll(".lib-row--album")].find((n) => n.textContent?.includes(name), )!; fireEvent.click(row); await waitFor(() => { const f = { hlRow: row.classList.contains("lib-row--hl"), hlTop: row.classList.contains("lib-row--hl-top"), hlTracks: listPane().querySelectorAll(".lib-scroll .lib-row--track.lib-row--hl").length, }; expect(f).toEqual({ hlRow: true, hlTop: true, hlTracks: 3 }); }); // a second album takes the highlight over — one footprint at a time const other = [...listPane().querySelectorAll(".lib-row--album")].find( (n) => n !== row && !n.classList.contains("lib-row--hl"), )!; fireEvent.click(other); await waitFor(() => { const a = { oldCleared: !row.classList.contains("lib-row--hl"), newHl: other.classList.contains("lib-row--hl"), }; expect(a).toEqual({ oldCleared: true, newHl: true }); }); }); expectNoDiagnostics(artifact); }); const queryBox = () => document.querySelector(".lib-query-input"); /** * The bar whose background says whether a search is on. It used to be the toolbar at the * top of the view; the field moved to the command line above the transport, and the wash * — which is a statement about the bar holding the text — went with it. */ const cmdLine = () => document.querySelector(".cmd-line")!; const queryValue = () => queryBox()?.value ?? ""; const queryCount = () => document.querySelector(".lib-query-count")?.textContent ?? ""; /** * What the user types. The box is a real , so typing is an input event * with the new value in it — that is what a browser fires, and simulating * keydowns instead would test a key-catcher we deliberately deleted. */ const typeOut = (s: string) => { const el = queryBox(); if (!el) throw new Error("the query box is not mounted"); fireEvent.input(el, { target: { value: `${el.value}${s}` } }); }; /** The same, for replacing the whole value (what selection + typing does). */ const setQueryValue = (v: string) => { const el = queryBox(); if (!el) throw new Error("the query box is not mounted"); fireEvent.input(el, { target: { value: v } }); }; it("`/` focuses the query field, which filters the list; Escape clears it", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const artistsShown = () => [...listPane().querySelectorAll(".lib-scroll .lib-row--artist .lib-section-name")].map( (n) => n.textContent, ); expect(artistsShown().length).toBeGreaterThan(1); // plain typing does NOT search — the rest of the keyboard is reserved for // hotkeys, which is the whole reason `/` exists. Keys that never reach the // field are the browser's normal page keys here, not typing. "cap" is // deliberately still a subsequence of the artist below: if a window key did // reach the filter, this assertion is the one that would notice — and it // avoids the reserved letters, which now *do* things (r plays a track). for (const ch of "cap") fireEvent.keyDown(window, { key: ch }); expect(queryValue()).toBe(""); expect(listPane().querySelectorAll(".lib-scroll .lib-row--track").length).toBeGreaterThan(0); // `/` hands the keyboard to the field, caret and all fireEvent.keyDown(window, { key: "/" }); await waitFor(() => expect(document.activeElement).toBe(queryBox())); expect(queryValue()).toBe(""); typeOut("carp"); await waitFor(() => expect(queryValue()).toBe("carp")); expect(queryCount()).toContain("tracks"); // the field stops being furniture the moment it holds a query (CSS keys off // this: an empty, unfocused slash is faint, a live one is the accent) and the // whole toolbar wears the search wash — jsdom cannot compute color-mix, so the // attributes the wash keys on are the contract worth pinning expect((queryBox()!.closest(".lib-query") as HTMLElement).dataset.empty).toBe("false"); expect(cmdLine().dataset.filtered).toBe("true"); expect(cmdLine().dataset.typing).toBe("true"); expect(cmdLine().dataset.none).toBe("false"); expect(queryBox()!.dataset.none).toBe("false"); await waitFor(() => expect(artistsShown()).toEqual(["Carpenter Brut"])); // only Carpenter Brut's tracks survive the filter expect(listPane().querySelectorAll(".lib-scroll .lib-row--track").length).toBe(9); // Enter accepts the filter: focus goes, the query stays, and the keyboard is // the list's again — which is the whole difference from Escape, below, which // undoes the query. (That the page's own keys resume is the disarmed-keyboard // test's job: it already asserts `g` flipping the view while nothing is // focused, and blur is the only thing Enter does here.) And nothing plays: // `/` asked to narrow the list, not to start music. fireEvent.keyDown(queryBox()!, { key: "Enter" }); await waitFor(() => expect(document.activeElement).not.toBe(queryBox())); expect(queryValue()).toBe("carp"); expect(listPane().querySelectorAll(".lib-scroll .lib-row--track").length).toBe(9); // and the bar stays lit: Enter gave the keyboard away, it did not end the // search — the list is still narrowed by text you are working on. (This is the // state that looked "still gray" once: the wash keyed on the caret alone.) expect(cmdLine().dataset.filtered).toBe("true"); expect(cmdLine().dataset.typing).toBe("false"); // and `/` goes back in for a *new* search: the second `/` is "ask again", so the // needle it finds is cleared rather than left in the field to be edited, and the // library behind the caret opens back up to the whole collection fireEvent.keyDown(window, { key: "/" }); await waitFor(() => expect(document.activeElement).toBe(queryBox())); await waitFor(() => expect(queryValue()).toBe("")); expect(cmdLine().dataset.filtered).toBe("false"); await waitFor(() => expect(listPane().querySelectorAll(".lib-scroll .lib-row--track").length).toBeGreaterThan(9), ); // typing "car" from scratch still matches all of Carpenter Brut setQueryValue("car"); await waitFor(() => expect(queryValue()).toBe("car")); await waitFor(() => expect(artistsShown()).toEqual(["Carpenter Brut"])); // a real query that matches nothing says so, in danger color's territory — and // the bar's wash follows the ink rather than staying accent, so "typing" and // "matched nothing" never wear the same hue typeOut("zz"); await waitFor(() => expect(queryCount()).toContain("no matches")); expect(queryBox()!.dataset.none).toBe("true"); expect(cmdLine().dataset.none).toBe("true"); expect(cmdLine().dataset.filtered).toBe("true"); expect(cmdLine().dataset.typing).toBe("true"); expect(listPane().querySelectorAll(".lib-scroll .lib-row--track").length).toBe(0); // Escape cancels the whole query, the library comes back (windowed: one // screenful holds three of the four artist headers) fireEvent.keyDown(queryBox()!, { key: "Escape" }); await waitFor(() => expect(queryValue()).toBe("")); await waitFor(() => expect(artistsShown().length).toBeGreaterThan(2)); }); expectNoDiagnostics(artifact); }); it("the disarmed keyboard stays reserved for hotkeys; `/` hands it to the search", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); // disarmed: letters are inert (not searches, not accidental commands) for (const ch of "cx") fireEvent.keyDown(window, { key: ch }); expect(queryValue()).toBe(""); // g still flips the view while disarmed (the existing contract) fireEvent.keyDown(window, { key: "g" }); await waitFor(() => expect(isInactive(listPane())).toBe(true)); // `/` from the grid pulls back to the list and arms the field fireEvent.keyDown(window, { key: "/" }); await waitFor(() => expect(isInactive(listPane())).toBe(false)); await waitFor(() => expect(document.activeElement).toBe(queryBox())); // once the field has focus, g is a letter, not a view flip — the INPUT // guard is the whole difference between a field and a key-catcher typeOut("g"); await waitFor(() => expect(queryValue()).toBe("g")); expect(isInactive(gridPane())).toBe(true); // and the browser's own editing keys reach the field: Ctrl-A (select all) // must not be swallowed by the hotkey layer's modifier guard, or the field // is a key-catcher with a border around it fireEvent.keyDown(queryBox()!, { key: "a", ctrlKey: true }); expect(isInactive(listPane())).toBe(false); // multi-word queries: spaces belong to the query, not to the page setQueryValue("gr t"); await waitFor(() => expect(queryValue()).toBe("gr t")); // Escape clears, and once empty it hands the keyboard back: a later `g` // flips the view again, typing does not silently re-arm fireEvent.keyDown(queryBox()!, { key: "Escape" }); await waitFor(() => expect(queryValue()).toBe("")); fireEvent.keyDown(queryBox()!, { key: "Escape" }); // empty → out of the field await waitFor(() => expect(document.activeElement).not.toBe(queryBox())); for (const ch of "x") fireEvent.keyDown(window, { key: ch }); expect(queryValue()).toBe(""); fireEvent.keyDown(window, { key: "g" }); await waitFor(() => expect(isInactive(gridPane())).toBe(false)); fireEvent.keyDown(window, { key: "Escape" }); // back to the list, stays inert await waitFor(() => expect(isInactive(gridPane())).toBe(true)); // Alt is reserved for exactly one binding here (Alt+r): Alt+g is a browser // or window-manager key, not a second route to the grid. fireEvent.keyDown(window, { key: "g", altKey: true }); await waitFor(() => expect(isInactive(gridPane())).toBe(true)); }); expectNoDiagnostics(artifact); }); it("pins the governing artist and album headers while scrolling inside them", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const scroller = listPane().querySelector(".lib-scroll")!; const stickyRows = () => [ ...listPane().querySelectorAll(".vlist-sticky .lib-row"), ]; const stickyText = () => stickyRows().map((n) => n.textContent ?? ""); // Aphex Twin block: [0] artist, [1] album "record 0", [2..4] its tracks. // Scroll to the middle of it: both headers must stay pinned on top. scroller.scrollTop = 3 * 30; fireEvent.scroll(scroller); await waitFor(() => expect(stickyText().length).toBe(2)); expect(stickyText()[0]).toContain("Aphex Twin"); expect(stickyText()[1]).toContain("record 0"); // scrolling on, inside the same album, must NOT rebuild the overlay — // the caller's cache means the same DOM nodes survive the frame const before = stickyRows(); scroller.scrollTop = 4 * 30; fireEvent.scroll(scroller); await waitFor(() => expect(stickyText()[1]).toContain("record 0")); const after = stickyRows(); expect(after.length).toBe(before.length); after.forEach((node, i) => expect(node).toBe(before[i])); // …and surviving the frame must not mean having stopped updating: the cached // copy is still a live row, so what lights up the original lights up the copy. // (It once did not: the overlay's DOM was built inside the memo that picked the // pair, so the next scroll frame disposed the bindings the cache kept handing // back — see `props.sticky`.) The cursor stays off the copy, by design. const pinnedAlbum = after[1]!; const realAlbum = [ ...listPane().querySelectorAll(".lib-scroll .lib-row--album"), ].find((r) => (r.textContent ?? "").includes("record 0"))!; expect(realAlbum).toBeTruthy(); fireEvent.click(realAlbum); await waitFor(() => expect(realAlbum.classList.contains("lib-row--hl")).toBe(true)); await waitFor(() => expect(pinnedAlbum.classList.contains("lib-row--hl")).toBe(true)); expect(pinnedAlbum.classList.contains("lib-row--cursor")).toBe(false); // into the next artist's block: the pinned pair follows scroller.scrollTop = 14 * 30; // Autechre's first album row fireEvent.scroll(scroller); await waitFor(() => expect(stickyText()[0]).toContain("Autechre")); expect(stickyText()[1]).toContain("Autechre record 0"); }); expectNoDiagnostics(artifact); }); it("arming with '/' keeps the scroll position; an actual query change resets it", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const scroller = listPane().querySelector(".lib-scroll")!; scroller.scrollTop = 300; fireEvent.scroll(scroller); await waitFor(() => expect(scroller.scrollTop).toBe(300)); // arming changes no results — the scroll must not move fireEvent.keyDown(window, { key: "/" }); await waitFor(() => expect(document.activeElement).toBe(queryBox())); expect(scroller.scrollTop).toBe(300); // leaving an empty query via Escape is equally inert fireEvent.keyDown(queryBox()!, { key: "Escape" }); await waitFor(() => expect(document.activeElement).not.toBe(queryBox())); expect(scroller.scrollTop).toBe(300); // the first character IS a filter change — jump to row 0 fireEvent.keyDown(window, { key: "/" }); typeOut("c"); await waitFor(() => expect(queryValue()).toBe("c")); await waitFor(() => expect(scroller.scrollTop).toBe(0)); // and so is the Escape that clears a real query back to the full list fireEvent.keyDown(queryBox()!, { key: "Escape" }); await waitFor(() => expect(queryValue()).toBe("")); scroller.scrollTop = 300; fireEvent.scroll(scroller); fireEvent.keyDown(window, { key: "/" }); typeOut("c"); await waitFor(() => expect(scroller.scrollTop).toBe(0)); }); expectNoDiagnostics(artifact); }); it("hides the inactive pane with inert, never aria-hidden", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); fireEvent.keyDown(window, { key: "g" }); // open the grid await waitFor(() => expect(gridPane().querySelectorAll(".album-cell").length).toBe(12)); // the exact shape Chrome flagged: focus lives inside the pane about to be // hidden (a real click leaves it there; jsdom keeps it by not moving focus) const cell = gridPane().querySelector(".album-cell")!; cell.focus(); expect(document.activeElement).toBe(cell); fireEvent.keyDown(window, { key: "Escape" }); // back to the list await waitFor(() => expect(isInactive(gridPane())).toBe(true)); // aria-hidden is *blocked* by Chrome on an ancestor of the focused element, // so it would silently leave the hidden grid exposed to assistive tech. expect(gridPane().getAttribute("aria-hidden")).toBeNull(); expect(gridPane().hasAttribute("inert")).toBe(true); expect(listPane().hasAttribute("inert")).toBe(false); }); expectNoDiagnostics(artifact); }); it("`g` toggles the view and Escape returns to the list", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); expect(isInactive(gridPane())).toBe(true); expect(isInactive(listPane())).toBe(false); fireEvent.keyDown(window, { key: "g" }); await waitFor(() => expect(isInactive(gridPane())).toBe(false)); expect(isInactive(listPane())).toBe(true); fireEvent.keyDown(window, { key: "g" }); await waitFor(() => expect(isInactive(listPane())).toBe(false)); fireEvent.keyDown(window, { key: "g" }); await waitFor(() => expect(isInactive(gridPane())).toBe(false)); fireEvent.keyDown(window, { key: "Escape" }); await waitFor(() => expect(isInactive(gridPane())).toBe(true)); // typing must not hijack the view — the search box is the next feature in // exactly these keys const input = document.createElement("input"); document.body.append(input); input.focus(); fireEvent.keyDown(input, { key: "g" }); expect(isInactive(gridPane())).toBe(true); input.remove(); }); expectNoDiagnostics(artifact); }); it("the toolbar is the harvest readout, and falls silent once the index is ready", async () => { // The app used to carry a header above the view: a wordmark and the collection // count. The count was the only part of it that said anything, and only while the // index was not yet on screen to be counted — so the header is gone and the // toolbar's count gutter carries the harvest instead. Mid-crawl it must say how // far the crawl has got; once there is nothing left to crawl it must stop saying // it, or we are back to a bar of chrome that repeats the list. let releaseCrawl!: () => void; const crawl = new Promise((r) => (releaseCrawl = r)); const server = navidromeFetch(songs); vi.stubGlobal("fetch", async (input: RequestInfo | URL) => { if (String(input).includes("/api/song")) await crawl; return server(input); }); saveConnection({ host: "https://nav.example.com", username: "admin", password: "wordpass" }); render(() => ); const toolbar = await waitFor(() => { const el = document.querySelector(".lib-toolbar"); expect(el?.querySelector(".harvest-status")).toBeTruthy(); return el!; }); // the counter lives beside the album count, and the crawl line is the toolbar's // own bottom border — both inside the bar, so neither adds a row above it expect(toolbar.contains(toolbar.querySelector(".harvest-status"))).toBe(true); expect(toolbar.querySelector('[role="progressbar"]')).toBeTruthy(); expect(toolbar.querySelector(".harvest-track--hidden")).toBeNull(); releaseCrawl(); await waitFor(() => expect(library().status()).toBe("ready"), { timeout: 3000 }); expect(toolbar.querySelector(".harvest-status")).toBeNull(); expect(toolbar.querySelector(".harvest-track--hidden")).toBeTruthy(); // the counts that are about the reading, not the harvesting, stay expect(toolbar.textContent).toContain("albums"); // The commit this bundle was built from, right-aligned in the same strip. It is a // build-time define rather than a fetched value, so in tests it is whatever the tree // running vitest was on — the assertion is that the app shows that exact stamp, and // shows nothing at all when the stamp is empty (a tree with no VCS). if (__COMMIT__) { expect(toolbar.querySelector(".lib-commit")?.textContent).toBe(__COMMIT__); } else { expect(toolbar.querySelector(".lib-commit")).toBeNull(); } }); /** * The stored query, in the shape the store writes it. Repeated here rather than * imported, as the login draft's key is (LoginDialog.test.tsx): the bytes in * localStorage are the contract under test, not an implementation detail. */ const QUERY_KEY = "hackermusic…y.v1"; const trackRows = () => listPane().querySelectorAll(".lib-scroll .lib-row--track").length; it("reloads into the search that was on screen", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); setQueryValue("carp"); await waitFor(() => expect(queryValue()).toBe("carp")); await waitFor(() => expect(trackRows()).toBe(9)); // stamped with the server it was typed against, which is what the two tests // below are actually about expect(JSON.parse(localStorage.getItem(QUERY_KEY)!)).toEqual({ server: "https://nav.example.com", text: "carp", }); // the reload: the storage survives, the components do not. The index is left // alone on purpose — a re-harvest would put a second crawl's worth of row work // inside this artifact's budget window, and the thing under test is what the // components remember, not what the server was able to answer twice. cleanup(); await bootConnected(); // the field carries it and the list is narrowed by it, without a keystroke expect(queryValue()).toBe("carp"); await waitFor(() => expect(trackRows()).toBe(9)); expect(queryCount()).toContain("tracks"); // restored, not armed: the caret is the list's until `/` asks for the field, // so the keyboard does not arrive in a text box nobody selected expect(document.activeElement).not.toBe(queryBox()); expect(cmdLine().dataset.filtered).toBe("true"); expect(cmdLine().dataset.typing).toBe("false"); // and it is still an ordinary query from here: Escape clears it, which // unfilters the list and takes the stored value with it fireEvent.keyDown(queryBox()!, { key: "Escape" }); await waitFor(() => expect(queryValue()).toBe("")); await waitFor(() => expect(trackRows()).toBeGreaterThan(9)); expect(JSON.parse(localStorage.getItem(QUERY_KEY)!)).toEqual({ server: "https://nav.example.com", text: "", }); }); expectNoDiagnostics(artifact); }); it("will not let another server's query filter this one", async () => { // The library is per-server, so a query from the previous host would leave this // one looking like an empty collection: the bar says "no matches", and nothing on // screen admits that a filter, let alone a server switch, is why. const { artifact } = await captureArtifact(async () => { await bootConnected(); const unfiltered = trackRows(); expect(unfiltered).toBeGreaterThan(9); cleanup(); library().reset(); localStorage.setItem( QUERY_KEY, JSON.stringify({ server: "https://other.example.com", text: "carp" }), ); await bootConnected(); expect(queryValue()).toBe(""); expect(cmdLine().dataset.filtered).toBe("false"); expect(queryCount()).toBe(""); expect(trackRows()).toBe(unfiltered); }); expectNoDiagnostics(artifact); }); it("reads a stored query of the wrong shape as no query at all", async () => { // The component reads `text` off the stored object during its first render, so a // value that is not the declared object has to be rejected on the way in rather // than reaching `text` as undefined: the filter treats an empty needle as "show // everything", while a query *looks* filtered (the bar's count gutter, the accent // on the slash) — an object missing its text would be a filtered list with no // visible text doing the filtering. const { artifact } = await captureArtifact(async () => { await bootConnected(); const unfiltered = trackRows(); cleanup(); library().reset(); // the host matches, so only the schema stands between this and a filter localStorage.setItem(QUERY_KEY, JSON.stringify({ server: "https://nav.example.com" })); await bootConnected(); expect(queryValue()).toBe(""); expect(cmdLine().dataset.filtered).toBe("false"); expect(trackRows()).toBe(unfiltered); }); expectNoDiagnostics(artifact); }); it("follows n and p to the middle of the list, and only once the row has left the screen", async () => { const { artifact } = await captureArtifact(async () => { // A screen ten rows tall, so the eleventh track is genuinely below the fold. stubResizeObserver({ width: 1000, height: 300 }); await bootConnected(); const scroller = listPane().querySelector(".lib-scroll")!; let stored = 0; Object.defineProperty(scroller, "scrollTop", { configurable: true, get: () => stored, set: (v: number) => { stored = v; }, }); // The rows the *view* builds, from the songs the library published — not the // fixture as written: a header the harvest earned is a row the view has and the // fixture does not, and the centring is measured in the view's rows. const rows = buildRows(library().songs()); const tracks = rows.flatMap((r, i) => (r.kind === "track" ? [{ row: i, song: r.song }] : [])); player().playSongs( tracks.slice(0, 14).map((t) => t.song), 0, ); await waitFor(() => expect(player().peekCurrent()?.id).toBe(tracks[0]!.song.id)); expect(stored).toBe(0); // The next record is already on screen. `n` answers it where it stands: a list // that slid on every press could not be read, which is why the reveal is // conditional rather than automatic. fireEvent.keyDown(window, { key: "n" }); await waitFor(() => expect(player().peekCurrent()?.id).toBe(tracks[1]!.song.id)); await new Promise((r) => setTimeout(r, 15)); expect(stored).toBe(0); // Walk on until the record is below the fold — and it arrives in the middle, // with as much list above it as below, which is what makes it readable as // "what is coming next" rather than "the row the browser happened to show". for (let k = 0; k < 9; k++) fireEvent.keyDown(window, { key: "n" }); const target = tracks[10]!; await waitFor(() => expect(player().peekCurrent()?.id).toBe(target.song.id)); await waitFor(() => expect(stored).toBe(target.row * 30 - (300 - 30) / 2)); // The row in the middle of the screen is the row being heard. const heard = [...scroller.querySelectorAll(".lib-row--track")].find((r) => r.classList.contains("lib-row--playing"), ); expect(heard?.textContent).toContain(target.song.title); // And the step back does not jitter: the previous row is on screen, so the list // holds still and only the marker moves. fireEvent.keyDown(window, { key: "p" }); await waitFor(() => expect(player().peekCurrent()?.id).toBe(tracks[9]!.song.id)); await new Promise((r) => setTimeout(r, 15)); expect(stored).toBe(target.row * 30 - (300 - 30) / 2); player().stop(); }); expectNoDiagnostics(artifact); });