import { beforeEach, describe, expect, it, vi } from "vitest"; import { createRoot, createSignal } from "solid-js"; import { rgbToOklch } from "colorthief/internals"; import type { LibrarySong } from "../harvest/types"; import type { ConnectionSettings } from "../subsonic/types"; import { ART_SIZE, accentSource, accentTokens, resetAccent, setAccentTrace, startAccentSync, type PaletteLoader, type Swatch, } from "./index"; import { DEFAULT_ACCENT, deriveAccent } from "./accent"; /** * The wiring, with the pixels supplied. * * What is under test is when a cover is asked for, who cancels it, and what a failure * leaves on screen — the arithmetic of choosing a colour is `accent.test.ts`'s business. * The loader is injected rather than the fetch stubbed, because the loader is where the * network, the decoder and the quantizer are all somebody else's problem. * * Every wait here is a `waitFor` rather than an `await` because both halves of the * wiring are effects and Solid 2 defers them: asking and painting are things that * happen a little after the signal that causes them, and a test that reads the DOM one * microtask later is asserting on a paint that has not been scheduled yet. */ const CONN: ConnectionSettings = { host: "https://nav.example.com", username: "a", password: "b" }; const STORAGE_KEY = "hackermusic.accent.v1"; const swatch = (l: number, c: number, h: number, proportion: number): Swatch => ({ oklch: () => ({ l, c, h }), proportion, }); /** A cover worth taking an accent from: a dark wall, and a print over 3% of it. */ const LENDABLE: Swatch[] = [swatch(0.18, 0.02, 250, 0.62), swatch(0.72, 0.22, 45, 0.03)]; /** A genuinely flat one: no hue anywhere, which is a different answer from greys. */ const FLAT: Swatch[] = [swatch(0.15, 0.0002, 250, 0.6), swatch(0.85, 0.0002, 90, 0.3)]; /** A black-and-white print with a cool temperature in it — the case that used to keep * the house green and should not: the print was shot through something. */ const COOL_PRINT: Swatch[] = [ swatch(0.12, 0.008, 255, 0.55), swatch(0.55, 0.012, 250, 0.3), swatch(0.9, 0.004, 245, 0.1), ]; /** A second record, and a different colour from the first. */ const ANOTHER: Swatch[] = [swatch(0.2, 0.02, 200, 0.7), swatch(0.65, 0.2, 300, 0.04)]; const painted = () => ({ accent: document.documentElement.style.getPropertyValue("--accent"), dim: document.documentElement.style.getPropertyValue("--accent-dim"), }); const worn = (palette: readonly Swatch[]) => deriveAccent({ color: palette[1]!, wall: palette[0]! }).tokens; /** Read a painted hex back into the space the decision was made in, to ask it what it did. */ const oklchOf = (hex: string) => { const byte = (at: number) => parseInt(hex.slice(at, at + 2), 16); return rgbToOklch(byte(1), byte(3), byte(5)); }; interface Harness { setCover(id: string | null): void; setConnection(conn: ConnectionSettings | null): void; /** Every (url, signal) the wiring has asked for, in order. */ asks: { url: string; signal: AbortSignal }[]; /** Hand the ask for this cover its palette. */ answer(id: string, palette: readonly Swatch[] | null): void; /** Reject the ask for this cover — a 404, or a decode that came back wrong. */ fail(id: string, e: unknown): void; } /** * Boot the wiring with a loader the test drives. * * Palettes are handed back only when the test answers them, which is what makes the * races testable at all: a track change mid-flight is a thing that has to be made to * happen rather than hoped for. */ function boot(): Harness { const [track, setTrack] = createSignal(null); const [connection, setConnection] = createSignal(CONN); const asks: { url: string; signal: AbortSignal }[] = []; const parked = new Map< string, { resolve: (p: readonly Swatch[] | null) => void; reject: (e: unknown) => void } >(); const loadPalette: PaletteLoader = (url, signal) => new Promise((resolve, reject) => { asks.push({ url, signal }); parked.set(idOf(url), { resolve, reject }); }); createRoot((dispose) => { roots.push(dispose); startAccentSync({ connection, track, loadPalette }); }); return { // The wiring is handed a track and works out which cover that means, exactly as the // bar does, so the test says which cover it wants and gets a song wearing it. setCover: (id) => setTrack(wearing(id)), setConnection, asks, answer: (id, palette) => parked.get(id)?.resolve(palette), fail: (id, e) => parked.get(id)?.reject(e), }; } const roots: (() => void)[] = []; const idOf = (url: string): string => new URL(url, "https://x").searchParams.get("id") ?? ""; /** A harvested row wearing one cover — enough of a song for the accent to ask about. */ const wearing = (coverId: string | null): LibrarySong | null => coverId === null ? null : { id: `mf-${coverId}`, title: "Annour", album: "Heavy Loop", albumId: `al-${coverId}`, source: "navidrome", coverArt: coverId, }; /** Wait until the cover the wiring is most recently asking about is this one. */ const asked = async (h: Harness, id: string) => { await vi.waitFor(() => expect(idOf(h.asks[h.asks.length - 1]!.url)).toBe(id)); }; beforeEach(() => { roots.splice(0).forEach((dispose) => dispose()); resetAccent(); localStorage.clear(); document.documentElement.style.removeProperty("--accent"); document.documentElement.style.removeProperty("--accent-dim"); }); describe("startAccentSync", () => { it("paints the record's colour on the root element", async () => { const h = boot(); h.setCover("a1"); await asked(h, "a1"); h.answer("a1", LENDABLE); await vi.waitFor(() => expect(painted()).toEqual(worn(LENDABLE))); expect(painted().accent).not.toBe(DEFAULT_ACCENT.accent); }); it("asks for the cover once, at palette size, from the id rather than a saved URL", async () => { const h = boot(); h.setCover("a1"); await asked(h, "a1"); h.answer("a1", LENDABLE); await vi.waitFor(() => expect(painted()).toEqual(worn(LENDABLE))); expect(h.asks).toHaveLength(1); const url = new URL(h.asks[0]!.url); expect(url.pathname).toBe("/rest/getCoverArt"); expect(url.searchParams.get("id")).toBe("a1"); expect(url.searchParams.get("size")).toBe(String(ART_SIZE)); // Authenticated like every other cover request: a palette nobody can fetch is a // theme that quietly never changes. expect(url.searchParams.get("u")).toBe("a"); expect(url.searchParams.get("t")).toBeTruthy(); expect(url.searchParams.get("s")).toBeTruthy(); }); it("asks nothing of a server it is not connected to, or of a track with no sleeve", async () => { const h = boot(); h.setCover(null); await vi.waitFor(() => expect(h.asks).toHaveLength(0)); h.setCover("a1"); h.setConnection(null); await vi.waitFor(() => expect(h.asks).toHaveLength(0)); // …and the no-connection case is not merely an effect that has not run yet: the // connection going away is itself a change the wiring sees. h.setCover(null); h.setConnection(CONN); h.setCover("a1"); await asked(h, "a1"); }); it("keeps the accent it has when the sleeve has nothing to lend", async () => { const h = boot(); h.setCover("a1"); await asked(h, "a1"); h.answer("a1", LENDABLE); await vi.waitFor(() => expect(painted()).toEqual(worn(LENDABLE))); const before = painted(); for (const [id, palette] of [ ["a2", FLAT], // no hue anywhere in it: nothing to take, and nothing to invent ["a3", []], // the quantizer found nothing ["a4", null], // the image would not decode ] as const) { h.setCover(id); await asked(h, id); h.answer(id, palette); await vi.waitFor(() => expect(painted()).toEqual(before)); } }); it("takes a colour off the black-and-white sleeve, from the print rather than the pixels", async () => { const h = boot(); h.setCover("a1"); await asked(h, "a1"); h.answer("a1", COOL_PRINT); // A greyscale record used to be a green bar: every swatch under `MIN_CHROMA` was // refused outright, which is right about the greys and wrong about the photograph. await vi.waitFor(() => expect(painted().accent).not.toBe(DEFAULT_ACCENT.accent)); const ink = oklchOf(painted().accent); expect(ink.h, "the print's own cool bias, not a hue the app chose").toBeCloseTo(250, -1); expect(ink.c, "enough chroma to read as a colour and not a smudge of grey").toBeGreaterThan( 0.03, ); }); it("the two greysheets are not the same colour, because the hue came from the print", async () => { const cool = boot(); cool.setCover("c"); await asked(cool, "c"); cool.answer("c", COOL_PRINT); await vi.waitFor(() => expect(painted().accent).not.toBe(DEFAULT_ACCENT.accent)); const cold = oklchOf(painted().accent).h; // The same palette with the temperature turned the other way: if the accent were // being invented rather than measured, these two would come out the same. The accent // is reset between them because it survives from the first boot by design — a record // that has said something keeps saying it until something newer does — and a test // that waits on "not the house green" would be watching the previous record. resetAccent(); const warm = boot(); warm.setCover("w"); await asked(warm, "w"); warm.answer( "w", COOL_PRINT.map((s) => swatch(s.oklch().l, s.oklch().c, 70, s.proportion)), ); await vi.waitFor(() => expect(painted().accent).not.toBe(DEFAULT_ACCENT.accent)); expect(Math.abs(oklchOf(painted().accent).h - cold)).toBeGreaterThan(60); }); it("says in the log what it decided, and which floor it fell at", async () => { // The reason this trace exists: "nothing to lend" was one sentence for four // different verdicts, and only the listener can say which floor was too high. So the // lines are worth pinning down — including the one that admits the colour on screen // belongs to a record that finished playing two tracks ago. setAccentTrace(true); const lines = vi.spyOn(console, "debug").mockImplementation(() => {}); const said = () => lines.mock.calls.map((c) => String(c[0])).join("\n"); try { const h = boot(); h.setCover("a1"); await asked(h, "a1"); h.answer("a1", COOL_PRINT); await vi.waitFor(() => expect(said()).toContain("off a colourless print shot through")); h.setCover("a2"); await asked(h, "a2"); h.answer("a2", FLAT); await vi.waitFor(() => expect(said()).toContain("too grey to wear")); expect(said()).toContain("no temperature to take: measured"); expect(said()).toContain("keeping"); // And the silence that started the whole investigation: a cover the wiring has // already read is not asked again, so coming back to it leaves the colour the // *later* record earned. The line says so; whether the behaviour should, is the // open question. h.setCover("a3"); await asked(h, "a3"); h.answer("a3", ANOTHER); await vi.waitFor(() => expect(painted().accent).toBe(worn(ANOTHER).accent)); h.setCover("a1"); await vi.waitFor(() => expect(said()).toContain("a1 already read")); expect(said()).toContain("worn since a3"); } finally { lines.mockRestore(); setAccentTrace(null); } }); it("keeps the accent it has when the server will not hand over the cover", async () => { const h = boot(); h.setCover("a1"); await asked(h, "a1"); h.answer("a1", LENDABLE); await vi.waitFor(() => expect(painted()).toEqual(worn(LENDABLE))); const before = painted(); h.setCover("a2"); await asked(h, "a2"); h.fail("a2", new Error("404 Not Found")); await vi.waitFor(() => expect(painted()).toEqual(before)); }); it("follows the record when the record changes", async () => { const h = boot(); h.setCover("a1"); await asked(h, "a1"); h.answer("a1", LENDABLE); await vi.waitFor(() => expect(painted()).toEqual(worn(LENDABLE))); h.setCover("a2"); await asked(h, "a2"); h.answer("a2", ANOTHER); await vi.waitFor(() => expect(painted()).toEqual(worn(ANOTHER))); expect(h.asks).toHaveLength(2); }); it("drops a palette that arrives after the track moved on", async () => { const h = boot(); h.setCover("a1"); await asked(h, "a1"); h.setCover("a2"); // a1 is still in flight await asked(h, "a2"); // The cancel is the part that matters: an abandoned ask is an abandoned request, not // merely an ignored answer, or skipping a track would leave a fetch running for it. expect(h.asks[0]!.signal.aborted).toBe(true); h.answer("a1", LENDABLE); // the late one await vi.waitFor(() => expect(painted()).toEqual(DEFAULT_ACCENT)); h.answer("a2", ANOTHER); await vi.waitFor(() => expect(painted()).toEqual(worn(ANOTHER))); }); it("paints the house pair before anything has been derived", async () => { boot(); // What is on screen in the seconds before a cover comes back — the stretch where an // unpainted root means a bar whose ink arrives a heartbeat after the bar does. await vi.waitFor(() => expect(painted()).toEqual(DEFAULT_ACCENT)); expect(accentSource()).toBeNull(); }); }); describe("the accent across a reload", () => { it("re-derives the record's colour on the first paint, and junk does not", async () => { const h = boot(); h.setCover("a1"); await asked(h, "a1"); h.answer("a1", LENDABLE); await vi.waitFor(() => expect(accentTokens()).toEqual(worn(LENDABLE))); // What is kept is the record's colour — the hue and chroma the cover lent, and the // wall it was chosen against — not the pair of hexes. The answer is a function of the // ground as well as the record, and the theme may have changed by the next page load; // the source is the theme-independent half, which is the only thing worth storing. expect(JSON.parse(localStorage.getItem(STORAGE_KEY)!)).toEqual({ from: { l: 0.72, c: 0.22, h: 45, proportion: 0.03 }, wall: { l: 0.18, c: 0.02, h: 250 }, }); // A fresh instance of the module is the next page load: the same storage, nothing in // memory, and no request yet — which is the whole reason a source rather than a swatch // cache is what gets kept. The dark pair comes back out of it, derived at boot. vi.resetModules(); const reloaded = await import("./index"); expect(reloaded.accentTokens("dark")).toEqual(worn(LENDABLE)); // …and the *same* stored colour re-derived for a light ground is a different pair of // ink, which is the entire reason the source rather than the answer is what is stored: // a cached answer would repaint the dark brightness after a reload into the light theme. const asLight = reloaded.accentTokens("light"); expect(asLight).not.toEqual(worn(LENDABLE)); expect(oklchOf(asLight.accent).l).toBeLessThan(0.69); // Storage is the one door anything can arrive through, so it is the one with a shape on // it: a value that is not a source reads as the absence it is, and the house pair comes // back rather than a half-read colour CSS would refuse to paint. localStorage.setItem(STORAGE_KEY, JSON.stringify({ accent: "red", dim: 4 })); vi.resetModules(); const junk = await import("./index"); expect(junk.accentTokens()).toEqual(DEFAULT_ACCENT); }); });