Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171import { afterEach, beforeEach, expect, it } from "vitest";import { cleanup, fireEvent, render, waitFor } from "@solidjs/testing-library";import { createSignal } from "solid-js";
import { albumCells } from "../lib/library/grid";import { buildRows } from "../lib/library/rows";import { forgetLandedCovers, markCoverLanded, SETTLE_MS } from "../lib/library/covers";import { clearConnection, saveConnection } from "../lib/connection";import type { LibrarySong } from "../lib/harvest/types";import { AlbumGrid } from "./AlbumGrid";
/** * The gallery's own contract with `<For>`: a window that says the same thing it * said before is the same window, node for node. * * `gridRows` mints a fresh array per row and `<For>` keys rows by array * identity, so without the memo's `equals` every republished cell list — a * harvest page landing, a favorite syncing, the observer measuring a width that * yields the same column count — disposed the whole window and built it again. * On an album grid that is the expensive kind of nothing: each rebuilt cell is * a new `<img>`, and each new `<img>` re-asks `getCoverArt` for a cover already * on the screen. That is what looked like the gallery refreshing itself. */
const song = (over: Partial<LibrarySong>): LibrarySong => ({ id: Math.random().toString(36).slice(2), title: "t", source: "navidrome", ...over,});
const library: LibrarySong[] = Array.from({ length: 6 }, (_, i) => song({ artist: i < 3 ? "Aphex Twin" : "Autechre", album: `Record ${i}`, albumId: `al-${i}`, coverArt: `art-${i}`, }),);
const cellsOf = (songs = library) => albumCells(buildRows(songs));
const cellsOfGrid = () => [...document.querySelectorAll<HTMLElement>(".album-cell")];const namesOfGrid = () => [...document.querySelectorAll<HTMLElement>(".album-name")];const askedCovers = () => [...document.querySelectorAll<HTMLImageElement>(".album-cell img.album-img")].map((i) => i.getAttribute("src"), );
/** Cover URLs need a server to ask, so the grid is connected for these. */const CONNECTION = { host: "https://nav.example.com", username: "admin", password: "wordpass" };
beforeEach(() => { localStorage.clear(); clearConnection(); saveConnection(CONNECTION); forgetLandedCovers();});
afterEach(() => { cleanup(); clearConnection(); localStorage.clear();});
it("lays out the rows it was told to: fixed cells, n per row", () => { // The row metric the virtualizer prices are fixed, so a row of cells is as // predictable as a row of tracks — and `columns` is a memo, which is what keeps // a width write that leaves the column count alone from reaching `gridRows`. render(() => ( <AlbumGrid cells={cellsOf()} onSelect={() => {}} columns={2} viewportHeight={500} /> )); expect([...document.querySelectorAll(".album-cellrow")].map((r) => r.children.length)).toEqual([ 2, 2, 2, ]);
// The same count is handed to the stylesheet, which lays each row out on that // many fixed tracks and centres them as a block. Dropped, the grid collapses to // a single column — so the handshake is asserted where the chunking is. expect( document.querySelector<HTMLElement>(".album-grid")!.style.getPropertyValue("--album-cols"), ).toBe("2");});
it("keeps the cells it already had when the library says the same thing again", async () => { const [cells, setCells] = createSignal(cellsOf()); render(() => <AlbumGrid cells={cells()} onSelect={() => {}} columns={3} viewportHeight={500} />);
const before = cellsOfGrid(); const beforeNames = namesOfGrid(); expect(before.length).toBe(6);
// A re-derivation of an unmoved library: new objects, new arrays, nothing new. setCells(cellsOf()); await Promise.resolve();
const after = cellsOfGrid(); expect(after).toHaveLength(before.length); after.forEach((node, i) => expect(node.isSameNode(before[i]!)).toBe(true)); // The captions are the same spans, not spans rebuilt to say the same words. expect(namesOfGrid()).toHaveLength(beforeNames.length); namesOfGrid().forEach((node, i) => expect(node.isSameNode(beforeNames[i]!)).toBe(true));});
it("asks for nothing it will not see: covers are held during a fling", async () => { // The complaint this answers: scrolling fast makes the covers of the albums you // stopped at take a second, because the albums you flew past asked for their // thumbnails first — and each of those is a server-side resample, on a // connection pool half a dozen wide. So a cell born mid-fling holds. const [cells, setCells] = createSignal(cellsOf()); render(() => <AlbumGrid cells={cells()} onSelect={() => {}} columns={3} viewportHeight={500} />); expect(askedCovers()).toHaveLength(6); // at rest, everything on screen is asked for
// One row in a single event: 200px against the capped interval is four rows a // second, which is a fling — and it stays inside the 416px of content, because // jsdom does not clamp `scrollTop` and scrolling past the end would empty the // window for a reason that has nothing to do with covers. const scroller = document.querySelector<HTMLElement>(".album-scroll")!; fireEvent.scroll(scroller, { target: { scrollTop: 200 } }); // …and the window is rebuilt while that motion is still in flight: a harvest // landing mid-fling, a favorite syncing — the same thing a fling does to the rows. setCells(cellsOf(library.map((s) => ({ ...s, artist: `${s.artist} & Band` })))); await waitFor(() => expect(cellsOfGrid()).toHaveLength(6));
// The tiles are all there, in their final shape, initials and all — and not one // byte has been asked for. expect(document.querySelectorAll(".album-art-ph")).toHaveLength(6); expect(askedCovers()).toHaveLength(0);
// When the motion stops, the queue is let go and what matters is asked for. await waitFor(() => expect(askedCovers()).toHaveLength(6), { timeout: SETTLE_MS * 5 });});
it("does not hold a cover this page has already seen", async () => { // A cover that landed earlier in the session is a memory-cache hit: it is not in // the queue's way, so holding it behind the queue would be a delay bought for // nothing — and it is the one thing that can answer while its neighbours wait. const [cells, setCells] = createSignal(cellsOf()); render(() => <AlbumGrid cells={cells()} onSelect={() => {}} columns={3} viewportHeight={500} />); const before = askedCovers(); expect(before).toHaveLength(6); markCoverLanded(before[2]!);
const scroller = document.querySelector<HTMLElement>(".album-scroll")!; fireEvent.scroll(scroller, { target: { scrollTop: 200 } }); setCells(cellsOf(library.map((s) => ({ ...s, artist: `${s.artist} & Band` })))); await waitFor(() => expect(cellsOfGrid()).toHaveLength(6));
expect(askedCovers()).toEqual([before[2]]); // just the one it already had});
it("rebuilds the window when a cover arrives, which is when it should", async () => { const [cells, setCells] = createSignal(cellsOf()); render(() => <AlbumGrid cells={cells()} onSelect={() => {}} columns={3} viewportHeight={500} />);
const before = cellsOfGrid(); const target = before.find((n) => n.title?.startsWith("Aphex Twin — Record 2"))!; expect(target).toBeDefined();
const moved = library.map((s) => (s.album === "Record 2" ? { ...s, coverArt: "art-new" } : s)); setCells(cellsOf(moved)); await Promise.resolve();
const after = cellsOfGrid(); expect(after).toHaveLength(6); // The tile that changed is a different node — the equality is a guard against // churn, not a refusal to update. expect(after.some((n) => n.isSameNode(target))).toBe(false); expect(after.map((n) => n.textContent)).toEqual(before.map((n) => n.textContent));});