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 { player } from "../lib/player"; import { TICK_MS } from "../lib/player/store"; import { detect } from "../lib/player/detect"; import { setWaveTrace } from "../lib/player/trace"; import { forgetMediaVerdicts } from "../lib/player/media"; import { levelToGain } from "../lib/player/volume"; import { mediaFiles, navidromeFetch, type FakeMediaFile } from "../test/navidrome"; import { FakeAudioContext, stubStreamFetch, type StreamFetchStub } from "../test/audio"; import { FakeWorker } from "../test/worker"; import type { DetectReply } from "../lib/player/detect.worker"; import { loopTrack } from "../test/signal"; import { stubResizeObserver } from "../test/env"; /** * The transport, mounted the way the app mounts it: under the connection gate, * as a sibling of the routed view. What is asserted is the contract a user can * feel — the bar is where it should be, the art is the current track's, the * thumb goes where it was dragged and stays there, and every control reaches * the player. */ const songs: FakeMediaFile[] = [ ...mediaFiles({ album: "Heavy Loop", albumArtist: "Autechre", albumId: "al-1" }, 3), ...mediaFiles({ album: "Amber", albumArtist: "Autechre", albumId: "al-2" }, 2, 3), ]; const bar = () => document.querySelector(".player-bar"); const seek = () => bar()!.querySelector(".pb-seek")!; const volume = () => bar()!.querySelector(".pb-volume")!; const repeatButton = () => bar()!.querySelector(".pb-repeat")!; const queueButton = () => bar()!.querySelector('[aria-label="Show queue"]')!; const clock = () => bar()!.querySelector(".pb-total")?.textContent ?? ""; const elapsed = () => bar()!.querySelector(".pb-elapsed")?.textContent ?? ""; const metaLines = () => [...bar()!.querySelectorAll(".pb-title, .pb-album, .pb-artist")].map((n) => n.textContent); const chips = () => [...bar()!.querySelectorAll(".pb-quality .lib-badge")].map((n) => ({ label: n.textContent ?? "", codec: n.dataset.codec, transcoded: n.dataset.transcoded === "true", })); const rowByTitle = (title: string) => [...document.querySelectorAll(".lib-row--track")].find( (r) => r.querySelector(".lib-title")?.textContent === title, )!; // The fake decoder's duration is the authoritative one (what the index carries // is metadata), so give it the fixture's real lengths per stream URL — otherwise // every track reports the fake's default 240s and the slider proves nothing. const SECONDS = new Map(songs.map((s) => [s.id, s.duration ?? 240])); class FakePlayerContext extends FakeAudioContext { constructor( opts: { undecodable?: string[]; decodedSeconds?: Record; /** what a stream decodes to, for the tests that run the real detector over bytes */ waveformFor?: (url: string) => Float32Array | undefined; } = {}, ) { super({ durationFor: (url) => { const id = new URL(url).searchParams.get("id") ?? ""; // The decoder's answer is the authoritative length, so a test that wants the // denominator the marks are placed by to differ from the one the index // published — which is the case the whole design turns on — has to be able to // say so, per track. return opts.decodedSeconds?.[id] ?? SECONDS.get(id) ?? 240; }, undecodable: opts.undecodable, waveformFor: opts.waveformFor, }); } } async function bootConnected( audio: { undecodable?: string[]; decodedSeconds?: Record; waveformFor?: (url: string) => Float32Array | undefined; } = {}, /** hold /rest/stream open, so the test decides when the bytes land */ stream: { delay?: boolean } = {}, ) { const stub = stubStreamFetch({ base: navidromeFetch(songs), delay: stream.delay }); vi.stubGlobal("fetch", stub.fetch); // the engine constructs the context with no arguments, so the fixture's // options have to be baked into the class the global points at vi.stubGlobal( "AudioContext", class extends FakePlayerContext { constructor() { super(audio); } }, ); 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).toBe(5)); return stub; } async function bootPlaying( title = "Track 1", audio: { undecodable?: string[]; decodedSeconds?: Record; waveformFor?: (url: string) => Float32Array | undefined; } = {}, ) { const stream = await bootConnected(audio); // by title, not by index: the list is sorted by album name, and a test that // clicked "the first row" would be asserting whatever the sort happens to // put there fireEvent.click(rowByTitle(title)); await waitFor(() => expect(player().peekState()).toBe("playing")); return stream; } beforeEach(() => { localStorage.clear(); clearConnection(); library().reset(); FakeWorker.reset(); // The repeat mode deserves its own reset, and does not get it from the line // above: a persisted signal keeps its value in memory as the source of truth and // reads localStorage only as a seed (see persist.ts), so clearing the disk half // leaves the store standing in last test's mode. Harmless while only a mouse // could reach it from this file; with `l` on the loop modes, any test can leave // the queue looping, and the next one would boot inside it. player().setRepeat("none"); // ...and the deck's octave, for the same reason and with the same consequence: it is persisted, // its in-memory value is the truth, and a test that pressed `]` would leave every later test in // the file playing an octave above the record it thinks it is hearing. player().setSpeed(1); player().setKey(0); player().setLock(false); // Same reasoning for the row's knobs, which are persisted signals too: a test that gave the pass a // wide stride to make it slow would leave every later test folding at that stride, and the failure // would surface as timeouts three files away from anything to do with waveforms. player().setWaveformTuning(null); setWaveTrace(false); player().dispose(); forgetMediaVerdicts(); FakeAudioContext.reset(); stubResizeObserver({ width: 1000, height: 0 }); }); afterEach(() => { player().dispose(); cleanup(); vi.unstubAllGlobals(); }); const audio = () => FakeAudioContext.instances[FakeAudioContext.instances.length - 1]!; /** stream requests asked for this track (and only this track) */ const urlsFor = (stub: StreamFetchStub, id: string | undefined) => stub.urls.filter((u) => new URL(u).searchParams.get("id") === id); it("appears under the list with the track's art, duration and controls", async () => { const { artifact } = await captureArtifact(async () => { // Nothing chosen yet: the row is on screen (that is where the waveform waits and grows) and the // transport is not, because art, clocks and controls are about a track or they are noise. Asserted on // the parts rather than on the footer, which is now always there. const stream = await bootConnected(); expect(bar()!.querySelector(".pb-art")).toBeNull(); expect(bar()!.querySelector(".pb-seek")).toBeNull(); expect(bar()!.querySelector(".pb-wave")!.hasAttribute("data-idle")).toBe(true); fireEvent.click(rowByTitle("Track 1")); await waitFor(() => expect(player().peekState()).toBe("playing")); expect(bar()!.querySelector(".pb-art")).toBeTruthy(); // it is a sibling of the routed view, not an overlay on top of it const parent = bar()!.parentElement!; expect(parent.querySelectorAll(".player-bar")).toHaveLength(1); const art = bar()!.querySelector("img.pb-art-img"); expect(art?.getAttribute("src")).toContain("/rest/getCoverArt"); // the track's own id, because the native API sends no artwork id and // getCoverArt resolves an entity id to that entity's cover expect(art?.getAttribute("src")).toContain("id=al-1-s0"); expect(art?.getAttribute("src")).toContain("size=88"); // 2× the 44px tile // title / album / artist, stacked in that order: what is playing, which // record it came from, who made it expect(metaLines()).toEqual(["Track 1", "Heavy Loop", "Autechre"]); // The bar is not in the tab order, and it does not keep focus either. This // app is driven by its own keys; a footer holding focus after a click takes // the keyboard from the list. Dragging with the mouse is unaffected. for (const el of [seek(), volume(), repeatButton(), queueButton()]) { expect(el.tabIndex, el.getAttribute("aria-label") ?? el.className).toBe(-1); } // the sliders hand focus straight back (they cannot refuse mousedown, which // is also what starts a drag), the buttons refuse mousedown itself for (const el of [seek(), volume()]) { el.focus(); expect(document.activeElement, el.className).not.toBe(el); } expect(fireEvent.mouseDown(repeatButton()), "repeat").toBe(false); expect(fireEvent.mouseDown(queueButton()), "queue").toBe(false); // elapsed at the start of the line, duration at its end — each labelling the // end it sits at, with the hairline running between them expect(elapsed()).toBe("0:00"); expect(clock()).toBe("0:30"); // the index's own duration, shown at once expect(Number(seek().max)).toBe(30); // the progress line is the row *under* the text, not a widget in the middle of // the top row: the bar is two rows, and the scrub spans both margins expect([...bar()!.children].map((c) => c.className)).toEqual(["pb-main", "pb-progress"]); expect(urlsFor(stream, player().peekCurrent()?.id)).toHaveLength(1); }); expectNoDiagnostics(artifact); }); it("crawls green over its own border while the track's bytes are in flight", async () => { const { artifact } = await captureArtifact(async () => { // A stream that does not answer until the test says so: the readout is about // the wait, so the wait has to be observable. const stream = await bootConnected({}, { delay: true }); const crawl = () => bar()!.querySelector(".pb-load-track"); // The bar is up before the sound is — the track is chosen, and its bytes are // still in the air, which is the exact moment that needs saying. fireEvent.click(rowByTitle("Track 1")); await waitFor(() => expect(bar()).toBeTruthy()); expect(player().peekState()).toBe("loading"); expect(crawl()).toBeTruthy(); // the same green as the harvest's, by rule rather than by copy: one track and // one bar, riding the bar's own top border as the toolbar's crawl rides the // toolbar's bottom one expect(crawl()!.querySelector(".pb-load-bar")).toBeTruthy(); // an overlay on the border, not a third row: the two rows of layout are alone expect([...bar()!.children].map((c) => c.className)).toEqual([ "pb-load-track", "pb-main", "pb-progress", ]); // Bytes land, readout gone — a wait that has ended has to stop being said. stream.pending[0]!.release(); await waitFor(() => expect(crawl()).toBeNull()); expect(player().peekState()).toBe("playing"); // …and it stays gone while the *next* track is in flight, which is most of a // listening session: gaplessness prefetches a track ahead of the clock, so a // bar that lit for any in-flight stream would crawl forever and say nothing. await waitFor(() => expect(stream.pending).toHaveLength(1)); // the prefetch expect(player().peekState()).toBe("playing"); expect(crawl()).toBeNull(); // nothing left hanging on the wire for the next test to trip over for (const p of stream.pending.slice()) p.release(); }); expectNoDiagnostics(artifact); }); it("the thumb goes where it was dragged, and stays there", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); const ctx = audio(); const played = player().peekCurrent()!.id; // mid-drag: the 250ms position sampler must not win the argument. Counted // per track, because the armed successor is also a source now and "the // sources" no longer means "the playbacks of this track". fireEvent.input(seek(), { target: { value: "12" } }); expect(seek().value).toBe("12"); expect(player().peekPosition()).toBeLessThan(1); // not seeked yet, not stuck expect(ctx.sourcesFor(played)).toHaveLength(1); // and the hairline's played part follows the finger, not the clock: the caret // marks the value and the accent behind it says how much is past. A fraction, // not a percentage — the component reports proportion and CSS multiplies, so // no float reaches the stylesheet as 40.00000000000001%. If Solid ever stopped // letting us write the property, this is the assertion that notices. await waitFor(() => expect(seek().style.getPropertyValue("--pb-fill")).toBe("0.4")); // the volume wears the same hairline, and its fill is the slider position — // the level, not the gain the log curve turns it into. Awaited, because a // bare signal write outside an event reaches effects on the next flush. player().setVolume(0.25); await waitFor(() => expect(volume().style.getPropertyValue("--pb-fill")).toBe("0.25")); // released: one new source, at the place the user let go fireEvent.change(seek(), { target: { value: "12" } }); await waitFor(() => expect(ctx.sourcesFor(played)).toHaveLength(2)); expect(ctx.sourcesFor(played)[1]!.startOffset).toBeCloseTo(12, 5); expect(seek().value).toBe("12"); // not yanked back to the sampled position }); expectNoDiagnostics(artifact); }); it("the repeat button walks none → album → artist → single, and the player agrees", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); expect(repeatButton().dataset.mode).toBe("none"); for (const mode of ["album", "artist", "single", "none"]) { fireEvent.click(repeatButton()); await waitFor(() => expect(repeatButton().dataset.mode).toBe(mode)); expect(player().peekRepeat()).toBe(mode); } }); expectNoDiagnostics(artifact); }); /** * The same four modes, from the keyboard. Asserted against the button rather than * only against the store because the button *is* the readout: it is out of the tab * order, so nothing else tells anyone which mode the key left the player in. If the * two ever stopped meaning one command — a second cycle order, a second write path — * this is the test that notices. */ it("`l` walks the loop modes the button walks, and the button says so", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); expect(player().peekRepeat()).toBe("none"); // The glyph is what the eye reads, and it is spelled per mode ("one", not // "single"), so the expected text travels with the mode rather than being // derived from it. const GLYPH = { none: "off", album: "album", artist: "artist", single: "one" } as const; for (const mode of ["album", "artist", "single", "none"] as const) { // pressed on the body, not on the button: the key is the window's, and it has // to reach the store from whatever the list happens to have focused. expect(fireEvent.keyDown(document.body, { key: "l" })).toBe(false); await waitFor(() => expect(repeatButton().dataset.mode).toBe(mode)); expect(player().peekRepeat()).toBe(mode); expect(repeatButton().textContent).toContain(GLYPH[mode]); expect(repeatButton().getAttribute("aria-label")).toBe(`Repeat ${mode}`); } // A focused button is no reason to abstain, either: unlike space, an `l` presses // nothing, so the key still turns the mode over with the button in the focus. repeatButton().focus(); fireEvent.keyDown(repeatButton(), { key: "l" }); await waitFor(() => expect(repeatButton().dataset.mode).toBe("album")); }); expectNoDiagnostics(artifact); }); it("`l` types where text is being typed, and leaves the modifiers to the browser", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); const before = player().peekRepeat(); // "le" is the start of a real band. The caret in the field is the caret in the // field, which is the same guard that keeps space out of the transport there. const box = document.querySelector(".lib-query-input")!; box.focus(); expect(fireEvent.keyDown(box, { key: "l" })).toBe(true); // untouched expect(player().peekRepeat()).toBe(before); box.blur(); // Cmd/Ctrl+L is the address bar and Alt+L somebody's tab switch: a key with a // modifier on is not this binding's to take, and taking it would cost the user // the one thing the key is for on every other page they visit. for (const mod of [{ ctrlKey: true }, { metaKey: true }, { altKey: true }]) { expect(fireEvent.keyDown(document.body, { key: "l", ...mod })).toBe(true); expect(player().peekRepeat()).toBe(before); } // Shift is not a modifier here but the shape of the letter: on a layout that // hides L behind Shift, Shift+L *is* how one types it, so "L" turns the mode // over exactly as "l" does. fireEvent.keyDown(document.body, { key: "L", shiftKey: true }); await waitFor(() => expect(player().peekRepeat()).toBe("album")); }); expectNoDiagnostics(artifact); }); it("`l` with nothing on the bar is the browser's, and leaves no mode behind", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); expect(player().peekState()).toBe("idle"); expect(bar()!.querySelector(".pb-loop")).toBeNull(); // No track, so no repeat button, so nothing to show the answer. A mode changed here would be a mode // nobody can see or undo, and a key that does something invisible is a key that reads as broken; the // browser keeps the letter. Asserted on the control rather than on the footer: with nothing loaded the // bar is on screen after all — the waiting row — and an assertion that the whole thing is missing was // always testing the wrong absence, which is why it is the one that broke. expect(fireEvent.keyDown(document.body, { key: "l" })).toBe(true); expect(player().peekRepeat()).toBe("none"); }); expectNoDiagnostics(artifact); }); /* ---------------------------------- A–B ---------------------------------- The region, from the keyboard: three presses of one key, and a bar that says which of the three it is standing in. What is asserted is what a listener can see — the hairline before the chip, the chip while the region lasts — and what they can hear, which is that the boundary was placed where the audio was rather than where the 250ms readout happened to be looking. */ const marks = () => bar()!.querySelector(".pb-marks"); const seekWrap = () => bar()!.querySelector(".pb-seek-wrap"); const markRegion = () => bar()!.querySelector(".pb-loop-region"); const markCaret = () => bar()!.querySelector(".pb-loop-caret"); const loopChip = () => bar()!.querySelector(".pb-loop"); it("`m` marks A, then B, then clears — and the bar says which of the three it is in", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); const played = player().peekCurrent()!.id; expect(marks()).toBeNull(); expect(loopChip()).toBeNull(); // A, ten seconds in. The clock is moved by the test — the fake's only moves when a // test says so — and the mark goes where the audio is: `peekLivePosition()`, not the // sampled position the readout runs on, because a boundary a quarter of a second off // is the bug this whole feature is a way of not having. audio().advance(10); expect(fireEvent.keyDown(document.body, { key: "m" })).toBe(false); expect(player().peekLoop()).toBeNull(); // half a region is not a region // Awaited, as every DOM read after a key press here is: a bare signal write from a // window listener reaches the bindings on the next flush, not during the press. await waitFor(() => expect(markCaret()).toBeTruthy()); // ...but it is drawn expect(markRegion()).toBeNull(); expect(loopChip()).toBeNull(); // no chip until there is a B // Where the audio is, not where the last sample said: 9.92s of a 30s track, on the // bytes' own length. The readout would have said 9.92 too, but only because the // ticker happened to be kept in step by the test; the live clock is the source. expect(Number(markCaret()!.style.getPropertyValue("--pb-loop-at"))).toBeCloseTo( (10 - 0.08) / 30, 5, ); // B, ten seconds of listening later. audio().advance(10); fireEvent.keyDown(document.body, { key: "m" }); const region = player().peekLoop()!; expect(region.start).toBeCloseTo(10 - 0.08, 2); expect(region.end).toBeCloseTo(20 - 0.08, 2); await waitFor(() => expect(loopChip()).toBeTruthy()); expect(markCaret()).toBeNull(); // the pending A is gone once there is a region expect(markRegion()).toBeTruthy(); expect(loopChip()!.textContent).toBe("A–B"); // Beside the repeat button — the two answers about what repeats, in one place — // out of the tab order, and refusing focus like everything else on the bar. expect(loopChip()!.parentElement).toBe(repeatButton().parentElement); expect(loopChip()!.tabIndex).toBe(-1); expect(fireEvent.mouseDown(loopChip()!), "loop chip").toBe(false); // The two seconds are in the tooltip, which is the only room the chip has for them. expect(loopChip()!.getAttribute("title")).toContain("0:09"); expect(loopChip()!.getAttribute("title")).toContain("0:19"); // and the boundary went onto the audio clock at the press, not at the next tick. The // playhead came back to A with it — pressing B reads the clock at the moment of the // press, so the press always lands exactly on its own boundary, and a pass that // started there would be a loop that never started. const bounded = audio().sourceFor(played)!; expect(bounded.startOffset).toBeCloseTo(10 - 0.08, 2); expect(bounded.stopAt).toBeCloseTo(bounded.startedAt! + 10, 5); // The third press clears, all of it, by key as well as by click. fireEvent.keyDown(document.body, { key: "m" }); await waitFor(() => expect(loopChip()).toBeNull()); expect(player().peekLoop()).toBeNull(); expect(marks()).toBeNull(); }); expectNoDiagnostics(artifact); }); it("a B that cannot be a region leaves the A standing, and the next press is another try", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); audio().advance(10); fireEvent.keyDown(document.body, { key: "m" }); // A await waitFor(() => expect(markCaret()).toBeTruthy()); // The same instant again: a region of nothing, refused — and refused by leaving the // bar in the state it was in. Resetting A here would mean the gesture had to start // over because of a press that did nothing, which reads as a key that eats requests. fireEvent.keyDown(document.body, { key: "m" }); expect(player().peekLoop()).toBeNull(); await waitFor(() => expect(markCaret()).toBeTruthy()); expect(loopChip()).toBeNull(); audio().advance(5); fireEvent.keyDown(document.body, { key: "m" }); const region = player().peekLoop()!; expect(region.start).toBeCloseTo(10 - 0.08, 2); // the A that survived the refusal expect(region.end).toBeCloseTo(15 - 0.08, 2); await waitFor(() => expect(loopChip()).toBeTruthy()); }); expectNoDiagnostics(artifact); }); it("the bar's own gesture ends the loop when it lands outside the marks", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); const played = player().peekCurrent()!.id; audio().advance(10); fireEvent.keyDown(document.body, { key: "m" }); // A audio().advance(10); fireEvent.keyDown(document.body, { key: "m" }); // B await waitFor(() => expect(loopChip()).toBeTruthy()); const region = player().peekLoop()!; // Let go between the marks, and the playhead moves while the loop stays where it was // put: "back to somewhere inside the bit I'm looping" is the commonest thing to want from // the bar once there is a loop on it, and a bar that answered it by dismantling the loop // would make the two controls fight. fireEvent.change(seek(), { target: { value: "15" } }); await waitFor(() => expect(player().peekPosition()).toBe(15)); expect(player().peekLoop()).toEqual(region); expect(loopChip()).toBeTruthy(); expect(markRegion()).toBeTruthy(); const kept = audio().sourcesFor(played).at(-2)!; // the live pass, not the one armed beside it at A expect(kept.startOffset).toBe(15); expect(kept.stopAt).toBeCloseTo(kept.startedAt! + (region.end - 15), 5); // Let go past the far mark, and the loop is over. The marks are the only place the region // is drawn, the slider underneath is the only thing on the row you can drag, and the hand // just carried the thumb out past the edge: that is saying *on past here*, and the audio // goes on from there instead of being fetched back to A for ever. fireEvent.change(seek(), { target: { value: "25" } }); await waitFor(() => expect(loopChip()).toBeNull()); expect(player().peekLoop()).toBeNull(); expect(marks()).toBeNull(); expect(player().peekPosition()).toBe(25); const leaving = audio().sourcesFor(played).at(-1)!; expect(leaving.startOffset).toBe(25); expect(leaving.stopAt, "a pass still bounded by a region nobody is looping").toBeUndefined(); }); expectNoDiagnostics(artifact); }); it("the marks are placed by the bytes, not by the length the index claimed", async () => { const { artifact } = await captureArtifact(async () => { const track = songs[0]!; // Track 1: the index says thirty seconds await bootPlaying("Track 1", { decodedSeconds: { [track.id!]: 30.4 } }); // The two denominators, in one place: the slider runs on the rounded claim, the // boundary on the exact bytes. They are meant to be different signals. expect(player().peekDuration()).toBe(30); expect(player().peekBufferDuration()).toBe(30.4); expect(Number(seek().max)).toBe(30); expect(player().setLoop({ start: 7.6, end: 22.8 })).toBe(true); // A quarter of the track, and half of it again — of 30.4. Against the rounded 30 the // marks would read 0.2533 and 0.5067, which is the difference between a mark on the // boundary and one next to it: the boundary is a place in the bytes, so that is the // only length a mark may be measured against. await waitFor(() => expect(markRegion()).toBeTruthy()); expect(Number(markRegion()!.style.getPropertyValue("--pb-loop-start"))).toBeCloseTo( 7.6 / 30.4, 6, ); expect(Number(markRegion()!.style.getPropertyValue("--pb-loop-width"))).toBeCloseTo( 15.2 / 30.4, 6, ); }); expectNoDiagnostics(artifact); }); /** The row, once it is drawing a track rather than waiting for one: the placeholder is on screen from boot, * so "the row exists" stopped being a useful sync point the moment the bar learned to wait. */ const measuredRow = () => waitFor(() => expect(wave()!.hasAttribute("data-idle")).toBe(false), { timeout: 3000 }); const wave = () => bar()!.querySelector(".pb-wave"); const wavePaths = () => [...bar()!.querySelectorAll(".pb-wave-path")]; it("waits with small bars when nothing is loaded, and claims no position while it waits", async () => { const { artifact } = await captureArtifact(async () => { // Nothing clicked, nothing decoded: the state the bar spent a long time rendering as an empty strip of // black. The placeholder exists so the arrival can be *seen* — the grow has somewhere to grow from — and // every assertion below is about keeping it a placeholder rather than a lie. await bootConnected(); await waitFor(() => expect(wave()).toBeTruthy()); expect(wave()!.hasAttribute("data-idle")).toBe(true); const d = wavePaths()[0]!.getAttribute("d") ?? ""; expect((d.match(/M/g) ?? []).length).toBeGreaterThan(50); // Short: mirrored bars top out at half the viewBox, and the placeholder is meant to sit near a fifth of // the row so that a track arriving is unmistakably more. Asserted on the path, because the whole point // is what the drawing claims, not what a class says. // The viewBox is 20 units tall and a mirrored bar measures at most half of it, so this is "no taller // than a third of the row" — short enough that a track arriving is unmistakably more, which is the whole // reason the placeholder is short rather than merely small. const heights = [...d.matchAll(/v([\d.]+)/g)].map((m) => Number(m[1])); expect(Math.max(...heights)).toBeGreaterThan(0); expect(Math.max(...heights)).toBeLessThan(20 / 3); // And no playhead: with no track there is no position, and an accent line at bucket zero would have the // placeholder pretending to be a transport. expect(bar()!.querySelector(".pb-wave-played")).toBeNull(); expect(bar()!.querySelector(".pb-wave-caret")).toBeNull(); }); expectNoDiagnostics(artifact); }); it("jumps to where the digits put it, and glides between ticks", async () => { const { artifact } = await captureArtifact(async () => { // The smoothing is a linear transition one tick long, which is arithmetically right for a clock that // advances linearly and wrong for one that has just been moved by hand: pressing `4` means *be at forty // percent*, not *watch the caret travel there*. So the row carries the glide duration, and the seek is // what turns it off for the one change it causes. // There is deliberately no "before the seek it glides" assertion here, and the reason is a finding: a // track *starting* also places the playhead, which is a jump by the same rule, so the honest answer at // boot is `0ms`. What the glide is for is a sample, and `store.test.ts` is where the clock can actually // be advanced far enough to prove the rule does not fire on one. await bootPlaying("Track 1", { waveformFor: () => LOOPY.samples }); await measuredRow(); player().seek(12); await waitFor(() => expect(wave()!.style.getPropertyValue("--pb-smooth")).toBe("0ms")); // And the jump is not only the caret's: both readers of `--pb-fill` inherit the duration from the row, // so the accent edge and the line on top of it move together — a playhead that jumped in one layer and // glided in the other would be the two-clock bug back again, wearing a smarter hat. expect(wave()!.style.getPropertyValue("--pb-tick")).toBe(`${TICK_MS}ms`); }); expectNoDiagnostics(artifact); }); it("grows the bars in once per measurement, and not again when the drawing changes", async () => { const { artifact } = await captureArtifact(async () => { // jsdom has no Web Animations, which is also the guard the component relies on — so the stub here is // doing double duty: it makes the call observable, and it proves the component never assumes `animate` // exists. What is being asserted is the *count*, because the count is the design: one grow per arrival, // not one per path rebuild. const played: string[] = []; const proto = globalThis.Element.prototype as unknown as { animate: (k: unknown, o: { duration?: number }) => void; }; const real = proto.animate; proto.animate = function (keyframes, options) { played.push(JSON.stringify({ keyframes, duration: options?.duration })); }; try { // Booting *into* a track is two arrivals, not one: the placeholder the bar was showing with nothing // loaded, then the track itself. That is the point of having a placeholder at all — an arrival from // nothing to something is invisible, and an arrival from a waiting silhouette to a real shape is not. await bootPlaying("Track 1", { waveformFor: () => LOOPY.samples }); await waitFor(() => expect(played.length).toBe(2)); expect(wave()).toBeTruthy(); // Transforms on the row, not rewrites of the path: the claim of cheapness rests on the compositor // doing the work, and a keyframe list that touched `d` or heights would say otherwise. for (const one of played) expect(one).toContain("scaleY"); // A look knob rebuilds the path and must not restart the grow: the fold republishes constantly while // a track loads, and a row that pulsed on every report is the failure the old lane design carried. player().setWaveformTuning({ barRatio: 0.85 }); await waitFor(() => expect(wavePaths()[0]!.getAttribute("d")).not.toContain("undefined")); await new Promise((r) => setTimeout(r, 50)); expect(played).toHaveLength(2); } finally { proto.animate = real; } }); expectNoDiagnostics(artifact); }); it("draws the row as the track's shape, mirrored about the row's own axis", async () => { const { artifact } = await captureArtifact(async () => { // A track with something in it. The default fixture is silence, and silence draws nothing here — // which is correct behaviour, not a bug, so a test of the drawing has to ask for samples. await bootPlaying("Track 1", { waveformFor: () => LOOPY.samples }); await measuredRow(); const peaks = player().peekPeaks()!; const d = wavePaths()[0]!.getAttribute("d") ?? ""; const marks = (d.match(/M/g) ?? []).length; // A thousand rectangles, as subpaths of one path — the count is the row's own budget, and the element // count is the thing the last design got wrong (144 of them, 252 ms a task), so both numbers are // asserted rather than one inferred from the other. expect(bar()!.querySelectorAll("rect")).toHaveLength(0); expect(marks).toBeGreaterThan(50); expect(marks).toBeLessThanOrEqual(1000); // Mirrored about the row's middle — the assertion for "it looks like a waveform over a line", checked in // the path rather than in a class name, because a class can say waveform while the geometry stands on its // floor. For these bars that is *one rect straddling the axis* rather than // two stacked on it — the shape is authored centred, so the assertion is that every mark crosses the // middle rather than that some marks are above it and some below. Checked in the geometry, because a // class can say "waveform" while the drawing stands on its floor. const boxes = [...d.matchAll(/M[\d.]+ ([\d.]+)h[\d.]+v([\d.]+)/g)].map((m) => [ Number(m[1]), Number(m[2]), ]); expect(boxes.length).toBeGreaterThan(20); const hs = boxes.map(([, h]) => h); expect(Math.max(...hs)).toBeGreaterThan(Math.min(...hs)); for (const [top, h] of boxes.slice(0, 40)) { expect(top).toBeLessThan(10); expect(top + h).toBeGreaterThan(10); } // …and they are the track's heights rather than one height: the row has dynamics in it. Deliberately a // relational claim — the fixture here is a synthetic melody whose loudest bucket happens to sit about // where the waiting placeholder does, so "taller than the placeholder" would be a claim about the // fixture rather than about the drawing. How short the placeholder is gets asserted on its own test, // against the viewBox, where no fixture is involved. // The row is a reading, not a control: no name, no focus, nothing addressable. (That it takes no // pointer events is `.pb-wave`'s CSS, which jsdom does not apply; what is checkable here is that there // is nothing on it to reach.) // The smoothing is one tick long, and the tick is the store's number, not one the stylesheet // invented: if the cadence ever changes and the glide does not, the playhead quietly stops landing on // the truth between samples. So the row is handed the duration, and the handoff is asserted. expect(wave()!.style.getPropertyValue("--pb-tick")).toBe(`${TICK_MS}ms`); expect(wave()!.getAttribute("aria-hidden")).toBe("true"); expect(wave()!.querySelector("a,button,[tabindex]")).toBeNull(); // Nothing is drawn where the pass has not been — the sentence the whole feature is built on, and the // one that does not change when the drawing does. In bucket units, so `filled` is the ruler. const right = Math.max( ...[...d.matchAll(/M([\d.]+) [\d.]+h([\d.]+)/g)].map((m) => Number(m[1]) + Number(m[2])), ); expect(right).toBeLessThanOrEqual(Math.max(1, peaks.filled)); // The playhead lives here now: one path drawn twice, the second cut to the position by a clip reading // `--pb-fill`, and a caret saying the same fact as a line. What matters is not that the parts exist but // that they read the *same* number the slider carries — the row's thumb left precisely so that the // position could be drawn in one place, and a second source for it would rebuild the thing that was // removed. const played = bar()!.querySelector(".pb-wave-played"); const caret = bar()!.querySelector(".pb-wave-caret"); expect(played).toBeTruthy(); expect(caret).toBeTruthy(); expect(played!.style.getPropertyValue("--pb-fill")).toBe( seek().style.getPropertyValue("--pb-fill"), ); expect(caret!.style.getPropertyValue("--pb-fill")).toBe( seek().style.getPropertyValue("--pb-fill"), ); // And it is a sibling of the row rather than part of the slider: the transport still answers a drag // with the strip on the bar, which is the reason the strip is allowed to be inert — and the drag is // what moves the playhead below it, from the same value. fireEvent.change(seek(), { target: { value: "20" } }); await waitFor(() => expect(player().peekPosition()).toBe(20)); await waitFor(() => expect( bar()!.querySelector(".pb-wave-played")!.style.getPropertyValue("--pb-fill"), ).toBe(seek().style.getPropertyValue("--pb-fill")), ); expect(seek().style.getPropertyValue("--pb-fill")).not.toBe("0"); }); expectNoDiagnostics(artifact); }); it("draws no strip for a track whose samples are all silence", async () => { const { artifact } = await captureArtifact(async () => { // Silence has a shape and it is the absence of one: an empty row is honest and a row of hairline-tall // marks would be claiming a floor that is not there. await bootPlaying("Track 1", { waveformFor: () => new Float32Array(44100 * 30) }); await waitFor(() => expect(player().peekPeaks()).toBeTruthy()); await waitFor(() => expect(bar()).toBeTruthy()); expect(wave()).toBeNull(); // The transport is untouched by the absence: the slider is still the row, as it always was. expect(bar()!.querySelector(".pb-seek")).toBeTruthy(); }); expectNoDiagnostics(artifact); }); it("the row is the waveform: no hairline playhead, and the slider still answers the drag", async () => { const { artifact } = await captureArtifact(async () => { // Three commits ago this test asserted the opposite — that the bar held no waveform at all — and it was // right then. The row came back by request, as the thing the row is: bars mirrored about the axis the // hairline used to be, so the line is gone rather than overlaid. What the old test was really guarding // survives the reversal: the transport must not lose its ability to be dragged, and nothing may draw a // second playhead. Both are asserted here, because both are the things a redesign breaks. await bootPlaying("Track 1", { waveformFor: () => LOOPY.samples }); await measuredRow(); // The drawing is inside the slider's own box, not a picture of one under it — which is what makes the // bars line up with the row instead of sitting beneath it. expect(wave()!.parentElement!.classList.contains("pb-seek-wrap")).toBe(true); // One path per layer, both layers the same drawing: the played part is a clip, not a second shape. const paths = wavePaths(); expect(paths).toHaveLength(2); expect(paths[0]!.getAttribute("d")).toBe(paths[1]!.getAttribute("d")); // The old playhead is gone from the row rather than hidden behind the new one: no `--pb-wave` reveal, // no third layer, and the only SVGs on the bar belong to the waveform. expect(bar()!.querySelectorAll("svg").length).toBe(2); for (const svg of bar()!.querySelectorAll("svg")) { expect( svg.parentElement!.classList.contains("pb-wave") || svg.parentElement!.classList.contains("pb-wave-played"), ).toBe(true); } // And the row is still a control: the slider underneath takes the drag, and the drawing follows the // same value rather than computing its own. expect(seek()).toBeTruthy(); fireEvent.change(seek(), { target: { value: "20" } }); await waitFor(() => expect(player().peekPosition()).toBe(20)); expect(seek().style.getPropertyValue("--pb-fill")).not.toBe(""); }); expectNoDiagnostics(artifact); }); it("draws the region as a rail beneath the wave, and takes the treatment from the knob", async () => { const { artifact } = await captureArtifact(async () => { // The attribute is the whole contract between the knob and the stylesheet: `App.css` picks the boundary // by `data-edge` — out of `--pb-edge-pattern` for the verticals, and out of `::before` for the rail. // The rail is what the row wears today because it is the treatment being judged: the slider's fill // already says how much has been heard, so the region's only job is to say *where*, and a rule laid // beneath the bars says it without standing in front of them. See `.pb-loop-region`. What is asserted // here is that the choice reaches the DOM at all, in both directions, without a re-fold. await bootPlaying(); player().setLoop({ start: 4, end: 12 }); await waitFor(() => expect(markRegion()).toBeTruthy()); expect(markRegion()!.dataset.edge).toBe("bar"); // The rail needs height the row does not have, so the row hands over a lane, and the attribute naming // the treatment on the *wrap* is what tells it to. Asserted here rather than in CSS because the failure // would be a DOM failure — the attribute reaching the wrap *is* the mechanism. expect(seekWrap()!.dataset.loopEdge).toBe("bar"); // Reserved, not grown. With the two presses gone the lane stays the row's — the wave does not take its // 5 px back the moment the region leaves, which is the whole difference between a lane and a growth: // pressing the key again puts ink somewhere that was already there, and the row's height, and with it // the two clocks either side of it, never moved. player().setLoop(null); await waitFor(() => expect(markRegion()).toBeNull()); expect(seekWrap()!.dataset.loopEdge).toBe("bar"); player().setLoop({ start: 4, end: 12 }); await waitFor(() => expect(markRegion()).toBeTruthy()); // …and the lane goes back with the treatment. Brackets draw their boundary between the bars, so they // hand the 5 px to the waveform: giving it back is what makes the two treatments comparable at all, // rather than one of them being judged at a quarter less height than the other. player().setWaveformTuning({ loopEdge: "brackets" }); await waitFor(() => expect(markRegion()!.dataset.edge).toBe("brackets")); expect(seekWrap()!.dataset.loopEdge).toBe("brackets"); player().setWaveformTuning({ loopEdge: "caps" }); await waitFor(() => expect(markRegion()!.dataset.edge).toBe("caps")); player().setWaveformTuning({ loopEdge: "solid" }); await waitFor(() => expect(markRegion()!.dataset.edge).toBe("solid")); player().setWaveformTuning({ loopEdge: "ticks" }); await waitFor(() => expect(markRegion()!.dataset.edge).toBe("ticks")); // A drawing knob: the boundary changes its ink and nothing else moves. The region is still the same // region at the same place in the bytes — the fold's own immunity to look knobs is asserted in // `peaks.test.ts`, where `foldKey` is the thing being checked. const placed = markRegion()!.style.getPropertyValue("--pb-loop-start"); player().setWaveformTuning({ loopEdge: "spine" }); await waitFor(() => expect(markRegion()!.dataset.edge).toBe("spine")); expect(markRegion()!.style.getPropertyValue("--pb-loop-start")).toBe(placed); expect(player().peekLoop()).toMatchObject({ start: 4, end: 12 }); player().setWaveformTuning(null); await waitFor(() => expect(markRegion()!.dataset.edge).toBe("bar")); expect(seekWrap()!.dataset.loopEdge).toBe("bar"); }); expectNoDiagnostics(artifact); }); /** * The marks, the chip and the key all wait for the same answer — there are bytes — and * this is the half that proves it: a stream that has not answered, on a track the index * says is thirty seconds long, has a timeline on the bar and nothing to mark on it. A * region set against that claim is a region that will not match the file that arrives. */ it("nothing is marked until the bytes arrive, whatever the index says the length is", async () => { const { artifact } = await captureArtifact(async () => { const stream = await bootConnected({}, { delay: true }); fireEvent.click(rowByTitle("Track 1")); await waitFor(() => expect(bar()).toBeTruthy()); expect(player().peekState()).toBe("loading"); expect(player().peekDuration()).toBe(30); // the index's number, and the slider's max expect(player().peekBufferDuration()).toBe(0); // no bytes, so nothing to measure expect(fireEvent.keyDown(document.body, { key: "m" })).toBe(false); // taken, refused expect(player().peekLoop()).toBeNull(); expect(marks()).toBeNull(); expect(loopChip()).toBeNull(); expect(player().setLoop({ start: 5, end: 20 })).toBe(false); // …and the moment they land, the same press works, because the same condition is met. stream.pending[0]!.release(); await waitFor(() => expect(player().peekState()).toBe("playing")); fireEvent.keyDown(document.body, { key: "m" }); await waitFor(() => expect(markCaret()).toBeTruthy()); for (const p of stream.pending.slice()) p.release(); }); expectNoDiagnostics(artifact); }); /** * The chip, the marks and the key all wait for the same answer — are the bytes here — * and a restored region is the case that tempts a bar to show it early: the session has a * pair of seconds, the index has a length to put them on, and neither of them is the file. * Nothing is drawn against a claim, and the reason is the two hands: a mark beside samples * that are not there yet is a promise the boundary cannot keep. */ it("a restored region stays off the bar until there are bytes to bound it", async () => { const { artifact } = await captureArtifact(async () => { const track = songs[0]!; localStorage.setItem( "hackermusic.player.session.v1", JSON.stringify({ server: "https://nav.example.com\u0000admin", ids: [track.id], at: track.id, atOffset: 3, loop: { at: track.id, start: 2, end: 8 }, }), ); const stream = await bootConnected({}, { delay: true }); await waitFor(() => expect(player().peekCurrent()?.id).toBe(track.id)); expect(player().peekState()).toBe("idle"); // nothing autoplayed to get here expect(player().peekLoop()).toEqual({ start: 2, end: 8 }); // the session's number expect(player().peekDuration()).toBe(30); // the index's claim, and the slider's max expect(player().peekBufferDuration()).toBe(0); // the bytes, of which there are none expect(loopChip(), "a chip for a region nothing is bounded by").toBeNull(); expect(marks()).toBeNull(); player().toggle(); // the space bar, which is the whole point of coming back await waitFor(() => expect(player().peekState()).toBe("loading")); expect(loopChip(), "a chip while the file is still coming").toBeNull(); expect(marks()).toBeNull(); // …and it appears when the answer arrives, without another press. stream.pending[0]!.release(); await waitFor(() => expect(player().peekState()).toBe("playing")); await waitFor(() => expect(loopChip()).toBeTruthy()); expect(audio().sourceFor(track.id!)!.stopAt).toBeDefined(); for (const p of stream.pending.slice()) p.release(); }); expectNoDiagnostics(artifact); }); /** * The four abstentions, and one non-abstention. * * The caret in the query box is typing, a modifier makes the key the browser's, a bar * that is not on screen has no readout to leave the answer in. A focused button is the * one that does *not* hold `m` back, and for the reason `l` gives: a button is muted for * space because space already presses it, and a letter presses nothing. */ it("`m` abstains where the bar abstains — typing, modifiers, and no bar at all", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); const box = document.querySelector(".lib-query-input")!; box.focus(); expect(fireEvent.keyDown(box, { key: "m" })).toBe(true); // untouched expect(player().peekLoop()).toBeNull(); expect(marks()).toBeNull(); box.blur(); for (const mod of [{ ctrlKey: true }, { metaKey: true }, { altKey: true }]) { expect(fireEvent.keyDown(document.body, { key: "m", ...mod })).toBe(true); expect(player().peekLoop()).toBeNull(); } // Shift+M is not a second gesture and is not swallowed either: the third `m` already // clears, so there is nothing for the shifted form to be. expect(fireEvent.keyDown(document.body, { key: "M", shiftKey: true })).toBe(true); expect(player().peekLoop()).toBeNull(); expect(marks()).toBeNull(); // A focused button still lets the letter through, exactly as the digits and `l` do. repeatButton().focus(); audio().advance(3); fireEvent.keyDown(repeatButton(), { key: "m" }); await waitFor(() => expect(markCaret()).toBeTruthy()); repeatButton().blur(); }); expectNoDiagnostics(artifact); }); it("`m` with nothing on the bar is the browser's, and leaves no region behind", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); // The waiting row is on screen; what is absent is the means to set a region. expect(bar()!.querySelector(".pb-loop")).toBeNull(); expect(fireEvent.keyDown(document.body, { key: "m" })).toBe(true); expect(player().peekLoop()).toBeNull(); }); expectNoDiagnostics(artifact); }); it("the chip is the other way out, and clearing it puts the queue back on the clock", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); audio().advance(10); fireEvent.keyDown(document.body, { key: "m" }); audio().advance(10); fireEvent.keyDown(document.body, { key: "m" }); await waitFor(() => expect(loopChip()).toBeTruthy()); expect(player().peekArmedNext()).toBeNull(); // stood down for the loop fireEvent.click(loopChip()!); await waitFor(() => expect(player().peekLoop()).toBeNull()); // The successor was armed against the boundary and cleared with it; nothing but the // clear re-arms it, and a queue that ran out at the end of this track because a loop // was cancelled minutes ago is not what standing down was meant to buy. await waitFor(() => expect(player().peekArmedNext()).toBeTruthy()); expect(player().peekArmedNext()).not.toBe(player().peekCurrent()?.id); }); expectNoDiagnostics(artifact); }); it("the volume slider is a position; the graph gets the gain that position means", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); fireEvent.input(volume(), { target: { value: "0.4" } }); await waitFor(() => expect(player().volume()).toBeCloseTo(0.4, 3)); // the readout stays in the units the control sits in, and says what the // position costs in the unit people actually think in expect(bar()!.textContent).toContain("40%"); expect(bar()!.querySelector(".pb-clock[title]")!.getAttribute("title")).toContain("-27.0 dB"); expect(audio().gains[0]!.gain.value).toBeCloseTo(levelToGain(0.4), 6); // the master gain // logarithmic means the *ratio* per step, so the same drag is the same // change in loudness at the bottom of the track as at the top fireEvent.input(volume(), { target: { value: "0.5" } }); await waitFor(() => expect(player().volume()).toBeCloseTo(0.5, 3)); const top = audio().gains[0]!.gain.value; fireEvent.input(volume(), { target: { value: "0.1" } }); await waitFor(() => expect(player().volume()).toBeCloseTo(0.1, 3)); const low = audio().gains[0]!.gain.value; fireEvent.input(volume(), { target: { value: "0.2" } }); await waitFor(() => expect(player().volume()).toBeCloseTo(0.2, 3)); const low2 = audio().gains[0]!.gain.value; expect(low2 / low).toBeCloseTo(top / levelToGain(0.4), 4); }); expectNoDiagnostics(artifact); }); /** * The two keys that belong to the volume slider, bound beside it: `+` and `-`, half a * decile of travel a press. They move the *stored level*, not the gain — the same number * the thumb moves — so a press and a drag cannot disagree about where the control is, and * the percentage the bar prints is the same story as the key that just changed it. */ it("`+`/`-` walk the volume, and the graph follows", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); player().setVolume(0.5); await waitFor(() => expect(volume().value).toBe("0.5")); // One press: 5% of travel, and the readout was told — the percent and the dB it // costs, which is the only way to tell a stepped key from a dead one. expect(fireEvent.keyDown(document.body, { key: "-" })).toBe(false); // prevented await waitFor(() => expect(player().volume()).toBeCloseTo(0.45, 6)); expect(volume().value).toBe("0.45"); // the thumb moved with it expect(bar()!.textContent).toContain("45%"); expect(audio().gains[0]!.gain.value).toBeCloseTo(levelToGain(0.45), 6); // Both spellings of each key: Shift is held for the glyph on most layouts, so the // unshifted forms have to answer too — `=` is an unshifted `+`, `-` an unshifted `_`. // Someone leaning on Shift between presses is asking for more or less, not for a key // that quietly stopped working halfway. fireEvent.keyDown(document.body, { key: "=" }); await waitFor(() => expect(player().volume()).toBeCloseTo(0.5, 6)); fireEvent.keyDown(document.body, { key: "+" }); await waitFor(() => expect(player().volume()).toBeCloseTo(0.55, 6)); fireEvent.keyDown(document.body, { key: "_" }); await waitFor(() => expect(player().volume()).toBeCloseTo(0.5, 6)); // Held down, autorepeat is a burst of presses inside one task — and each still moves, // because the step reads the store's shadow rather than the signal (peekVolume). for (let i = 0; i < 6; i++) fireEvent.keyDown(document.body, { key: "-" }); await waitFor(() => expect(player().volume()).toBeCloseTo(0.2, 6)); // rounded to the slider's own 1%, so twenty presses end to end is exactly 0 and // exactly 1 rather than a percent with float dust on it expect(bar()!.textContent).toContain("20%"); // ...and the ends clamp instead of running off: silence has no room below it. for (let i = 0; i < 10; i++) fireEvent.keyDown(document.body, { key: "-" }); await waitFor(() => expect(player().volume()).toBe(0)); expect(audio().gains[0]!.gain.value).toBe(0); // a mute that is really a mute fireEvent.keyDown(document.body, { key: "-" }); expect(player().volume()).toBe(0); for (let i = 0; i < 30; i++) fireEvent.keyDown(document.body, { key: "+" }); await waitFor(() => expect(player().volume()).toBe(1)); expect(audio().gains[0]!.gain.value).toBe(1); // A focused button does not swallow these the way it swallows space — space *is* how you // press one, and a button does nothing with a minus, so the level still answers from // wherever the pointer last left the page. The same bargain the number row struck, and // the check that these two did not join space's exception list by accident. player().setVolume(0.5); const repeat = repeatButton(); const mode = repeat.getAttribute("aria-label"); repeat.focus(); expect(fireEvent.keyDown(repeat, { key: "-" })).toBe(false); await waitFor(() => expect(player().volume()).toBeCloseTo(0.45, 6)); expect(repeat.getAttribute("aria-label")).toBe(mode); // the button it landed on did not press }); expectNoDiagnostics(artifact); }); it("`+`/`-` answer with nothing loaded, and abstain where the rest of the bar abstains", async () => { const { artifact } = await captureArtifact(async () => { // The one key on this bar that does not need a track: the master gain is a fact about // the room, not about a song — and arriving at a crawl of a library at full volume is // the commonest reason to want it. The bar is not even on screen here (it is drawn only // once there is a track to describe), which is the point: the level set before the // first play is the level that play arrives at. await bootConnected(); expect(player().peekCurrent()).toBeNull(); // No slider, because there is no track to play: the level is set from the keyboard and nothing else. expect(bar()!.querySelector(".pb-volume")).toBeNull(); player().setVolume(0.5); fireEvent.keyDown(document.body, { key: "-" }); await waitFor(() => expect(player().volume()).toBeCloseTo(0.45, 6)); // typing: "-1" and "±" are queries, and a search box that could not type a minus // because the bar took the key is the bug this guard exists to prevent. fireEvent.keyDown(window, { key: "/" }); const box = document.querySelector(".lib-query-input")!; await waitFor(() => expect(document.activeElement).toBe(box)); expect(fireEvent.keyDown(box, { key: "-" })).toBe(true); // untouched expect(fireEvent.keyDown(box, { key: "+" })).toBe(true); expect(player().volume()).toBeCloseTo(0.45, 6); // modifiers are somebody else's shortcut — Cmd/Ctrl +/- is the browser's zoom, and a // second answer to it in the same keystroke is a volume that moves while the page does fireEvent.keyDown(document.body, { key: "+", metaKey: true }); fireEvent.keyDown(document.body, { key: "-", ctrlKey: true }); fireEvent.keyDown(document.body, { key: "-", altKey: true }); expect(player().volume()).toBeCloseTo(0.45, 6); }); expectNoDiagnostics(artifact); }); it("`{`/`}` snap the deck's speed, and the deck is set with nothing on the bar", async () => { const { artifact } = await captureArtifact(async () => { // The other half of the `+`/`-` pair, and it takes the same exemption from needing a record: // the speed belongs to the deck, so the press is not thrown away because the deck has nothing // on it yet. As with the level, what is set before the first play is what the first play // arrives at. await bootConnected(); expect(player().peekCurrent()).toBeNull(); // The deck has a speed before it has a track; the readout that would show it does not exist yet. expect(bar()!.querySelector(".pb-varispeed")).toBeNull(); expect(fireEvent.keyDown(document.body, { key: "}" })).toBe(false); // prevented: we took it await waitFor(() => expect(player().peekSpeed()).toBe(2)); // ...and nothing invented a glyph to show for it: with no bar there is nowhere to wear one. expect(document.querySelector(".pb-varispeed")).toBeNull(); // Direction, and the ends of the travel. A held key is a burst of presses, and a wrap would // mean somebody leaning on `}` a half-second too long came out the other side of the record. fireEvent.keyDown(document.body, { key: "{" }); fireEvent.keyDown(document.body, { key: "{" }); await waitFor(() => expect(player().peekSpeed()).toBe(0.5)); for (let i = 0; i < 6; i++) fireEvent.keyDown(document.body, { key: "}" }); await waitFor(() => expect(player().peekSpeed()).toBe(2)); // The unshifted pair beside them is a different control, and this is the assertion that keeps it // that way: `]` moves the pitch and must not touch the speed, or the two features are one // feature wearing two keys. const before = player().peekSpeed(); fireEvent.keyDown(document.body, { key: "]" }); fireEvent.keyDown(document.body, { key: "[" }); fireEvent.keyDown(document.body, { key: "[" }); expect(player().peekSpeed()).toBe(before); // modifiers are somebody else's shortcut: Cmd/Ctrl+[ is the browser's own back, and the // second answer to it in the same keystroke is a page that navigates while the record shifts. fireEvent.keyDown(document.body, { key: "}", metaKey: true }); fireEvent.keyDown(document.body, { key: "{", ctrlKey: true }); fireEvent.keyDown(document.body, { key: "}", altKey: true }); expect(player().peekSpeed()).toBe(2); // what the keys were for, in the end: every source the deck arms from here carries the // setting — the track and the successor armed beside it, both, because it is the deck that is // running and not one node of it. fireEvent.click(rowByTitle("Track 1")); await waitFor(() => expect(player().peekState()).toBe("playing")); await waitFor(() => expect(audio().sources.length).toBeGreaterThan(1)); expect(audio().sources.every((s) => s.playbackRate.value === 2)).toBe(true); expect(document.querySelector(".pb-varispeed")?.textContent).toBe("\u00d72"); }); expectNoDiagnostics(artifact); }); it("`[`/`]` move the key without moving the clock, and `\\` decides whether the speed may move it", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); const id = player().peekCurrent()!.id; const key = () => document.querySelector(".pb-pitch")?.textContent ?? null; // Counted rather than asserted to be one: the deck may already have a successor in the air, and // how many sources a booted track has is nobody's claim here. What matters is that the number // does not move when the key does. const arms = () => audio().sourcesFor(id).length; const armed = arms(); // A semitone a press, in the direction the bracket points, with the readout appearing on the // first one — and the readout is the whole of the feedback, so a glyph that disagreed with the // state would be the bug a listener would feel as the key "not working". expect(key()).toBeNull(); fireEvent.keyDown(document.body, { key: "]" }); fireEvent.keyDown(document.body, { key: "]" }); fireEvent.keyDown(document.body, { key: "]" }); await waitFor(() => expect(player().peekKey()).toBe(3)); await waitFor(() => expect(key()).toBe("+3st")); fireEvent.keyDown(document.body, { key: "[" }); await waitFor(() => expect(player().peekKey()).toBe(2)); await waitFor(() => expect(key()).toBe("+2st")); // Nothing was re-armed, and this is the claim the whole feature is built on: the shifter sits on // the master, so a key pressed mid-phrase moves the pitch at its next frame and leaves the // running source — its rate, its boundary, its seam — exactly where it was. A key change that // cost a new source would be a key change that cost the loop under it. expect(arms()).toBe(armed); expect(audio().sourceFor(id)!.playbackRate.value).toBe(1); // The ends of the travel, held: 30 presses of `]` reach two octaves and stop there rather than // running into a shifter that has no answer for +30. for (let i = 0; i < 30; i++) fireEvent.keyDown(document.body, { key: "]" }); await waitFor(() => expect(player().peekKey()).toBe(24)); // The lock, and the reset three keys away. With the speed at ×1 the lock has nothing to hold, // so the readout is still only the key — a badge that reads "lock" while changing nothing is a // badge nobody trusts. fireEvent.keyDown(document.body, { key: "\\" }); await waitFor(() => expect(player().locked()).toBe(true)); await waitFor(() => expect(key()).toBe("+24st")); fireEvent.keyDown(document.body, { key: "\\" }); await waitFor(() => expect(player().locked()).toBe(false)); // ...and now that the speed *is* moving the pitch, the lock is doing work: \u00d72 with the lock on is // the record an octave fast and at the pitch it was written at, which is the sentence this whole // feature exists to make true. fireEvent.keyDown(document.body, { key: "}" }); await waitFor(() => expect(player().peekSpeed()).toBe(2)); // The contrast, in the same breath: the *speed* is the one that has to tear a source down and // arm another, because a BufferSource's rate is fixed at `start()`. The key never does this. expect(arms()).toBeGreaterThan(armed); fireEvent.keyDown(document.body, { key: "\\" }); await waitFor(() => expect(player().locked()).toBe(true)); // +24 asked for, −12 to cancel the octave, clamped at the two octaves the shifter reaches. await waitFor(() => expect(key()).toBe("+12st·lock")); expect(audio().sourceFor(id)!.playbackRate.value).toBe(2); // One key for the whole state, because the state is one decision: the listener who has had // enough of the experiment wants the record back, not the record back three times. fireEvent.keyDown(document.body, { key: "|" }); await waitFor(() => expect(player().peekKey()).toBe(0)); expect(player().locked()).toBe(false); expect(player().peekSpeed()).toBe(1); await waitFor(() => expect(key()).toBeNull()); // and the record is playing at its own speed again: a slower source is not a source that was // corrected, it is the next one, armed for the second the old one was stopped at. expect(audio().sourceFor(id)!.playbackRate.value).toBe(1); }); expectNoDiagnostics(artifact); }); it("space pauses and resumes — and is not a scroll key while music is playing", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); expect(player().peekState()).toBe("playing"); // false === the default was prevented, which is the only way to tell "we // took the key" from "nothing happened to it" expect(fireEvent.keyDown(document.body, { key: " " })).toBe(false); await waitFor(() => expect(player().peekState()).toBe("paused")); const id = player().peekCurrent()!.id; expect(audio().sourceFor(id)!.stopped).toBe(true); // not resumed by flipping the old one: a BufferSource cannot be restarted const arms = audio().sourcesFor(id).length; expect(fireEvent.keyDown(document.body, { key: " " })).toBe(false); await waitFor(() => expect(player().peekState()).toBe("playing")); expect(audio().sourcesFor(id)).toHaveLength(arms + 1); }); expectNoDiagnostics(artifact); }); it("space types where text is being typed, and a focused button keeps its activation", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); // a query is allowed to contain a space; the caret is in the field, so the // key belongs to the field (multi-word filters die without this) const box = document.querySelector(".lib-query-input")!; box.focus(); fireEvent.input(box, { target: { value: "carp" } }); const state = player().peekState(); expect(fireEvent.keyDown(box, { key: " " })).toBe(true); // untouched expect(player().peekState()).toBe(state); // Space *is* how you press a focused button. If the transport answered here // too, the pause and the resume would land in one keystroke and the key would // look broken. (jsdom does not synthesise the button's click from a keydown, // so only our half of the story can be asserted — that we kept out of it.) const repeat = bar()!.querySelector("button[aria-label^='Repeat']")!; repeat.focus(); expect(fireEvent.keyDown(repeat, { key: " " })).toBe(true); expect(player().peekState()).toBe(state); }); expectNoDiagnostics(artifact); }); it("space with nothing playing is still the list's scroll key", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); expect(player().peekState()).toBe("idle"); expect(bar()!.querySelector(".pb-loop")).toBeNull(); // the bar is not even on screen; stealing space here would cost the key its // only useful job, so the browser keeps it expect(fireEvent.keyDown(document.body, { key: " " })).toBe(true); expect(player().peekState()).toBe("idle"); }); expectNoDiagnostics(artifact); }); /* ------------------------------ the number row ----------------------------- */ it("the number row seeks: one key per tenth of the track", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); const ctx = audio(); const played = player().peekCurrent()!.id; expect(player().peekDuration()).toBe(30); // the fixture's own length, deciles exact // `5` is the middle of the *track* — not of the queue, which is what a key // named after a position on the progress line has to mean — and the source // armed at 15s is the proof it reached the audio clock rather than the label. expect(fireEvent.keyDown(document.body, { key: "5" })).toBe(false); await waitFor(() => expect(ctx.sourcesFor(played)).toHaveLength(2)); expect(ctx.sourcesFor(played)[1]!.startOffset).toBe(15); expect(elapsed()).toBe("0:15"); // the readout was told, not just the graph // `9` is nine tenths in and `0` is the restart, both of which the slider // already did with a mouse; this is the same `seek`, reached from the keys. // The 9 does not land on 27: the store keeps a few seconds of tail on any // start, because a track that begins two seconds from its end is // indistinguishable from one that has finished — and the thumb's far end // answers with the same number, which is the point of going through `seek` // rather than inventing a second route to the timeline. for (const [key, at] of [ ["9", 25], ["0", 0], ["3", 9], ] as const) { const arms = ctx.sourcesFor(played).length; fireEvent.keyDown(document.body, { key }); await waitFor(() => expect(ctx.sourcesFor(played)).toHaveLength(arms + 1)); expect(ctx.sourcesFor(played)[arms]!.startOffset).toBe(at); } }); expectNoDiagnostics(artifact); }); it("digits type in the query box, and a focused button does not mute them", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); const ctx = audio(); const played = player().peekCurrent()!.id; const arms = ctx.sourcesFor(played).length; // "dmo" is a band and "0781" is an album. A digit that jumped the timeline // while the caret was in the field would make the box unusable in a way nobody // notices until they give up on searching for numbers. const box = document.querySelector(".lib-query-input")!; box.focus(); expect(fireEvent.keyDown(box, { key: "5" })).toBe(true); // untouched expect(ctx.sourcesFor(played)).toHaveLength(arms); // Space has to back off from a focused button because it *is* how you press // one; a digit presses nothing, so the transport still answers with the button // in focus. Asserting the guard did not spread is the point. const repeat = bar()!.querySelector("button[aria-label^='Repeat']")!; repeat.focus(); expect(fireEvent.keyDown(repeat, { key: "5" })).toBe(false); await waitFor(() => expect(ctx.sourcesFor(played)).toHaveLength(arms + 1)); expect(ctx.sourcesFor(played)[arms]!.startOffset).toBe(15); }); expectNoDiagnostics(artifact); }); it("digits with nothing loaded are the browser's", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); expect(player().peekState()).toBe("idle"); expect(bar()!.querySelector(".pb-loop")).toBeNull(); // Nothing to move, so the key is left alone rather than swallowed by a seek to // zero — which would look like a track that restarts whenever it feels like it. for (const key of ["0", "5", "9"]) { expect(fireEvent.keyDown(document.body, { key })).toBe(true); } expect(player().peekState()).toBe("idle"); expect(player().peekCurrent()).toBeNull(); }); expectNoDiagnostics(artifact); }); it("a digit thrown at the player mid-flight is honoured when the bytes land", async () => { const { artifact } = await captureArtifact(async () => { const stream = await bootConnected(); // The other hard case: the key arrives while the track is still being fetched, // when there is no timeline to move. The offset has to be kept and handed to // the first source, or the keypress is quietly dropped whenever the network is // slower than the typing — which is most of the time, on the first track of an // album, which is when someone is most likely to punch ahead. fireEvent.click(rowByTitle("Track 1")); expect(player().peekCurrent()).not.toBeNull(); fireEvent.keyDown(document.body, { key: "5" }); await waitFor(() => expect(player().peekState()).toBe("playing")); expect(audio().sourceFor(player().peekCurrent()!.id)!.startOffset).toBe(15); // One fetch for the track, restarted at the offset — not a rewind-and-retry, // and not counting the prefetch of whatever comes next, which is a second // stream URL by design and would make this assertion true for the wrong reason. expect(urlsFor(stream, player().peekCurrent()?.id)).toHaveLength(1); }); expectNoDiagnostics(artifact); }); it("a digit while paused is where the track resumes", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); const ctx = audio(); const played = player().peekCurrent()!.id; fireEvent.keyDown(document.body, { key: " " }); await waitFor(() => expect(player().peekState()).toBe("paused")); // Paused is the branch of `seek` with no live source to tear down, so the // offset has nowhere to go but a variable — the one the resume has to remember // a moment later. Nothing new is armed while stopped, either: a pause that // started a source would be audible. const arms = ctx.sourcesFor(played).length; expect(fireEvent.keyDown(document.body, { key: "3" })).toBe(false); expect(ctx.sourcesFor(played)).toHaveLength(arms); expect(player().peekPosition()).toBe(9); fireEvent.keyDown(document.body, { key: " " }); await waitFor(() => expect(player().peekState()).toBe("playing")); expect(ctx.sourcesFor(played)[arms]!.startOffset).toBe(9); }); expectNoDiagnostics(artifact); }); it("says what the track is made of, under the cover", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); // Two chips from the same trackBadges() the rows use — codec and bitrate, // the pair that answers "what am I hearing, and is it the file on the // server". Bit depth and sample rate stay in the rows, which have room for // four; a third box here would be wider than the cover it sits under. expect(chips().map((c) => c.label)).toEqual(["flac", "900k"]); expect(chips()[0]).toMatchObject({ codec: "flac", transcoded: false }); // under the tile, not over it — the caption reads below what it labels const left = bar()!.querySelector(".pb-left")!; expect([...left.children].map((c) => c.className)).toEqual(["pb-art", "pb-quality"]); }); expectNoDiagnostics(artifact); }); it("when the browser refused the original, the chip says what is really playing", async () => { const { artifact } = await captureArtifact(async () => { // the file is ALAC in an m4a, which this fake browser cannot decode; the // server then serves a transcode, and a chip still reading "alac" would be // the bar lying about the one thing a local player exists to report const filed = { suffix: songs[0]!.suffix, codec: songs[0]!.codec }; songs[0]!.suffix = "m4a"; songs[0]!.codec = "alac"; forgetMediaVerdicts(); try { await bootPlaying("Track 1", { undecodable: ["raw"] }); } finally { // the fixture array is shared with every other test in this file, and the // one above reads this track's chips too songs[0]!.suffix = filed.suffix; songs[0]!.codec = filed.codec; } const [codec] = chips(); expect(codec!.label).toBe("flac"); // what was served, not what was filed expect(codec!.transcoded).toBe(true); expect(bar()!.querySelector(".pb-quality")!.getAttribute("title")).toContain("alac"); // the rest still describes the file, which is the only truth available expect( chips() .slice(1) .map((c) => c.label), ).toEqual(["900k"]); }); expectNoDiagnostics(artifact); }); it("the queue button is honest about doing nothing yet", async () => { const { artifact } = await captureArtifact(async () => { const stream = await bootPlaying(); const before = player().peekState(); fireEvent.click(queueButton()); expect(player().peekState()).toBe(before); expect(urlsFor(stream, player().peekCurrent()?.id)).toHaveLength(1); expect(queueButton().textContent).toContain("5"); // the whole list is queued }); expectNoDiagnostics(artifact); }); /* ------------------------------ artwork zoom ------------------------------ */ const artTile = () => bar()!.querySelector("button.pb-art")!; const zoom = () => document.querySelector(".art-modal"); const zoomImg = () => zoom()?.querySelector("img.art-img"); const gridCells = () => document.querySelectorAll(".album-cell").length; it("clicking the cover blows it up — and asks for it at that size", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); expect(zoom()).toBeNull(); // It is a button, so it refuses focus like the rest of the bar: the footer // must not take the keyboard from the list, zoomed or not. expect(fireEvent.mouseDown(artTile()), "art tile").toBe(false); fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); const overlay = zoom()!; expect(overlay.getAttribute("role")).toBe("dialog"); expect(overlay.getAttribute("aria-modal")).toBe("true"); // the keyboard landed on what just opened expect(document.activeElement).toBe(overlay); // A second getCoverArt, at the size it is actually being shown (2× for a 2× // screen) rather than the 88px tile stretched across the window… const src = zoomImg()!.getAttribute("src")!; expect(src).toContain("/rest/getCoverArt"); expect(src).toContain("id=al-1-s0"); expect(src).toContain("size=1440"); // …and the tile underneath is still the small one expect(bar()!.querySelector("img.pb-art-img")!.getAttribute("src")).toContain("size=88"); // who and what, under the picture — and nothing else on top of it: the overlay is // a sleeve, not a tool, so it carries no close button and no instructions expect(overlay.querySelector(".art-caption-line")?.textContent).toBe("Autechre — Heavy Loop"); expect(overlay.querySelector(".art-close")).toBeNull(); expect(overlay.querySelector(".art-hint")).toBeNull(); expect(overlay.querySelectorAll("button")).toHaveLength(0); // the tile says so while its own overlay is up expect(artTile().getAttribute("data-open")).toBe("true"); }); expectNoDiagnostics(artifact); }); it("Esc, Enter, and a click anywhere put the cover away", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); expect(fireEvent.keyDown(document.body, { key: "Escape" })).toBe(false); await waitFor(() => expect(zoom()).toBeNull()); // A click means "done" wherever it lands, on the picture included: with no // control in the overlay, there is nothing a click could have been reaching for. fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); fireEvent.click(zoom()!); await waitFor(() => expect(zoom()).toBeNull()); // Enter is the keyboard's other exit, so a dialog does not have a default control // that silently does nothing. fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); fireEvent.keyDown(document.body, { key: "Enter" }); await waitFor(() => expect(zoom()).toBeNull()); // closed is closed: the tile is not left stuck in its open state expect(artTile().getAttribute("data-open")).toBe("false"); }); expectNoDiagnostics(artifact); }); it("the queue running out puts the cover away with the track it was a picture of", async () => { // Every way out above is the listener's. This one is the queue's, and it is the only one the overlay // cannot get by asking: the picture is of the current track, so when the last record ends there is nothing // left for it to be a picture of — and a modal over a library with nothing playing is the one state where // the bar has taken the page back and returns neither music nor list. The footer outlives every track, so // it is asserted staying. const { artifact } = await captureArtifact(async () => { await bootPlaying(); fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); player().stop(); // the same call the queue makes past its last record await waitFor(() => expect(zoom()).toBeNull()); expect(bar()).toBeTruthy(); expect(bar()!.querySelector(".pb-art")).toBeNull(); }); expectNoDiagnostics(artifact); }); it("the overlay takes the keys: nothing behind it moves", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); // grid up, so there is something for a stray Escape to break fireEvent.keyDown(window, { key: "g" }); await waitFor(() => expect(gridCells()).toBe(2)); fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); // Escape closes the overlay and stops there. The library binds Escape on the // same window to mean "back to the list", so one key would otherwise close // the cover *and* change the view underneath it. expect(fireEvent.keyDown(document.body, { key: "Escape" })).toBe(false); await waitFor(() => expect(zoom()).toBeNull()); expect(gridCells(), "Escape collapsed the grid behind it").toBe(2); // …and a key the overlay has no use for is swallowed rather than thrown at // the list behind it fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); fireEvent.keyDown(document.body, { key: "j" }); fireEvent.keyDown(document.body, { key: "g" }); expect(zoom(), "a swallowed key closed the overlay").toBeTruthy(); expect(gridCells(), "g reached the library behind the overlay").toBe(2); // Tab is the exception: it is how a keyboard user reaches the ×, and an // overlay that ate it would be a room with no door. expect(fireEvent.keyDown(document.body, { key: "Tab" })).toBe(true); expect(zoom()).toBeTruthy(); }); expectNoDiagnostics(artifact); }); it("space is still the transport with the cover up — pausing to look is allowed", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); expect(player().peekState()).toBe("playing"); expect(fireEvent.keyDown(document.body, { key: " " })).toBe(false); await waitFor(() => expect(player().peekState()).toBe("paused")); // the key paused the music; it did not close the thing it was read from expect(zoom()).toBeTruthy(); }); expectNoDiagnostics(artifact); }); it("the number row is still the transport with the cover up — the timeline outlives the art", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); const played = player().peekCurrent()!.id; fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); // The overlay swallows the list's keys, and it should; the timeline is not one // of them. Someone with a cover filling the window is still listening, and // "skip the bit I can hear coming" is the other thing they do without putting // the art away — so the deciles pass through to the transport, un-prevented, // exactly as Space does. expect(fireEvent.keyDown(document.body, { key: "3" })).toBe(false); await waitFor(() => expect(audio().sourcesFor(played)).toHaveLength(2)); expect(audio().sourcesFor(played)[1]!.startOffset).toBe(9); expect(zoom(), "a seek closed the overlay").toBeTruthy(); }); expectNoDiagnostics(artifact); }); it("`l` is still the transport with the cover up — the loop outlives the art", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); // The overlay owns the keyboard while it is up, and the repeat button is part // of what it covers — so a key that could not get through would leave the mode // unchangeable for as long as someone is admiring a cover, which is precisely // when they are also deciding how far the queue should run. Same handoff as the // deciles: past the capture handler, un-prevented, to the transport. expect(fireEvent.keyDown(document.body, { key: "l" })).toBe(false); await waitFor(() => expect(player().peekRepeat()).toBe("album")); expect(zoom(), "a mode change closed the overlay").toBeTruthy(); }); expectNoDiagnostics(artifact); }); it("`m` is still the marker with the cover up — a loop is set while the music plays", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); // The overlay owns the keyboard, and this is the key it has the least business // taking: a loop is decided while the track is playing, and the commonest reason the // cover is up is that the track is playing. Swallowing it would make the feature // unusable at exactly the moment it is wanted — and the marks it draws are on the bar // underneath the art. Same handoff as space, the deciles and `l`. audio().advance(10); expect(fireEvent.keyDown(document.body, { key: "m" })).toBe(false); audio().advance(10); expect(fireEvent.keyDown(document.body, { key: "m" })).toBe(false); await waitFor(() => expect(player().peekLoop()).toBeTruthy()); expect(player().peekLoop()!.end).toBeGreaterThan(player().peekLoop()!.start); expect(zoom(), "marking a region closed the overlay").toBeTruthy(); }); expectNoDiagnostics(artifact); }); it("the blown-up cover follows the track, and a failed one does not blacklist the next", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); fireEvent.click(artTile()); await waitFor(() => expect(zoomImg()).toBeTruthy()); expect(zoomImg()!.getAttribute("src")).toContain("id=al-1-s0"); // the fade is driven by the load, not by the element existing expect(zoom()!.querySelector(".art-stage")!.getAttribute("data-loaded")).toBe("false"); fireEvent.load(zoomImg()!); await waitFor(() => expect(zoom()!.querySelector(".art-stage")!.getAttribute("data-loaded")).toBe("true"), ); // A cover that will not arrive: the placeholder stays, and no is left // strutting a broken-image icon. fireEvent.error(zoomImg()!); await waitFor(() => expect(zoomImg()).toBeNull()); expect(zoom()!.querySelector(".art-ph")?.textContent).toBe("HL"); // Heavy Loop // …and the next record's art still arrives. A `failed` boolean would have // hidden this one too. player().playAt(0); // the other album, wherever the sort put it await waitFor(() => expect(player().peekCurrent()?.album).toBe("Amber")); await waitFor(() => expect(zoomImg()?.getAttribute("src")).toContain("id=al-2-s")); expect(zoom()!.querySelector(".art-stage")!.getAttribute("data-loaded")).toBe("false"); }); expectNoDiagnostics(artifact); }); it("a track with no picture of its own wears its record's", async () => { const { artifact } = await captureArtifact(async () => { // The case the grid has always got right and the bar has always got wrong: a // record whose sleeve is a cover image in its folder, so no file reports a // picture of its own and Navidrome marshals nothing about the album's. The bar // asks the record, which is the same id the cell for this album in the grid // asks for — and `imageAbsent` stays unset, because a server that found the // art in the folder has settled the opposite. const arted = songs.map((s) => s.hasCoverArt); songs.forEach((s) => (s.hasCoverArt = false)); try { await bootPlaying(); const art = bar()!.querySelector("img.pb-art-img"); // the album's own id, and not a sibling's either: the grid asks for this same // id for this same record, and Navidrome caches one picture per record under it expect(art?.getAttribute("src")).toContain("id=al-1&size=88"); expect(art?.getAttribute("src")).toContain("size=88"); expect(artTile().disabled).toBe(false); expect(bar()!.querySelector(".pb-art-ph")!.textContent).toBe("HL"); // under it, as ever // and the blown-up copy is the same record at its own size, not the 88px // tile stretched across a window fireEvent.click(artTile()); await waitFor(() => expect(zoomImg()?.getAttribute("src")).toContain("id=al-1&size=1440")); } finally { songs.forEach((s, i) => (s.hasCoverArt = arted[i])); } }); expectNoDiagnostics(artifact); }); it("a record the server says has no sleeve is never asked for one", async () => { const { artifact } = await captureArtifact(async () => { // The settled answer (`imageAbsent`) is worth having precisely because a modern // Navidrome will happily answer the question with a generic grey placeholder // instead of a refusal: a bar that asked anyway would paint the server's // stock artwork over the app's own initials, which is the one thing the // untagged directory on the disk does not need. const arted = songs.map((s) => ({ hasCoverArt: s.hasCoverArt, imageAbsent: s.imageAbsent })); songs.forEach((s) => { s.hasCoverArt = false; s.imageAbsent = true; }); try { await bootPlaying(); expect(bar()!.querySelector("img.pb-art-img")).toBeNull(); expect(artTile().disabled).toBe(true); fireEvent.click(artTile()); expect(zoom()).toBeNull(); } finally { songs.forEach((s, i) => Object.assign(s, arted[i])); } }); expectNoDiagnostics(artifact); }); it("a record that refuses the question keeps its initials", async () => { const { artifact } = await captureArtifact(async () => { // A server that has never filed a picture for the folder and answers the ask // with a refusal (an older Navidrome, or one that has resolved nothing). The // tile learns it from the failed load and stops advertising art: the initials // were the honest picture all along, and a clickable tile onto nothing is a // control that lies. const arted = songs.map((s) => s.hasCoverArt); songs.forEach((s) => (s.hasCoverArt = false)); try { await bootPlaying(); expect(bar()!.querySelector("img.pb-art-img")).toBeTruthy(); fireEvent.error(bar()!.querySelector("img.pb-art-img")!); await waitFor(() => expect(bar()!.querySelector("img.pb-art-img")).toBeNull()); expect(bar()!.querySelector(".pb-art-ph")!.textContent).toBe("HL"); expect(artTile().disabled).toBe(true); expect(artTile().getAttribute("data-has-art")).toBe("false"); fireEvent.click(artTile()); expect(zoom()).toBeNull(); } finally { songs.forEach((s, i) => (s.hasCoverArt = arted[i])); } }); expectNoDiagnostics(artifact); }); /** * Paused is otherwise invisible on the bar: there is no play/pause button (space is the * transport), the clocks that would show it sit two rows away, and "the number stopped" * is the least legible way to say a track is stopped on purpose. So the art — the half of * the bar that names the track — wears the mark. */ it("the art wears the paused mark, and only while the track is stopped", async () => { const { artifact } = await captureArtifact(async () => { await bootPlaying(); // Playing: no mark, and the tile is still just the way in to the cover. expect(artTile().querySelector(".paused-mark")).toBeNull(); expect(artTile().getAttribute("aria-label")).toBe("Enlarge artwork"); fireEvent.keyDown(document.body, { key: " " }); // the transport, as ever await waitFor(() => expect(player().peekState()).toBe("paused")); expect(artTile().querySelector(".paused-mark")).toBeTruthy(); // ...and said out loud as well as in ink: the mark is a drawing (aria-hidden), so the // button's own name is the only way a reader learns the track is stopped. expect(artTile().getAttribute("aria-label")).toBe("Enlarge artwork · paused"); expect(artTile().getAttribute("title")).toBe("Artwork · paused"); // Resuming takes it off — the mark belongs to the state, not to the track having been // paused at some point, and a stale pair of bars is a paused button nobody can press. fireEvent.keyDown(document.body, { key: " " }); await waitFor(() => expect(player().peekState()).toBe("playing")); expect(artTile().querySelector(".paused-mark")).toBeNull(); expect(artTile().getAttribute("aria-label")).toBe("Enlarge artwork"); }); expectNoDiagnostics(artifact); }); it("the mark is on whichever art the user is looking at", async () => { const { artifact } = await captureArtifact(async () => { // Blown up, the bar that carries the mark is behind the backdrop — and space still // pauses behind the overlay, which is exactly when the mark is wanted and the one // place it cannot be seen. So the stage carries its own, at the size of the picture. await bootPlaying(); fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); expect(zoom()!.querySelector(".paused-mark")).toBeNull(); fireEvent.keyDown(document.body, { key: " " }); await waitFor(() => expect(player().peekState()).toBe("paused")); expect(zoom()!.querySelector(".paused-mark")).toBeTruthy(); }); expectNoDiagnostics(artifact); }); it("the mark goes over the initials when the server has no covers at all", async () => { const { artifact } = await captureArtifact(async () => { // A directory of untagged files is the common case, and there the initials *are* the // art: what the mark reports is the track, not the picture of it. The fake says so // the way a settled server does — no picture in the file, none on the record — // because an unanswered question is one the bar goes and asks. const arted = songs.map((s) => ({ hasCoverArt: s.hasCoverArt, imageAbsent: s.imageAbsent })); songs.forEach((s) => { s.hasCoverArt = false; s.imageAbsent = true; }); try { await bootPlaying(); expect(bar()!.querySelector("img.pb-art-img")).toBeNull(); expect(bar()!.querySelector(".pb-art-ph")!.textContent).toBeTruthy(); // the initials expect(player().peekState()).toBe("playing"); fireEvent.keyDown(document.body, { key: " " }); await waitFor(() => expect(player().peekState()).toBe("paused")); expect(artTile().querySelector(".paused-mark")).toBeTruthy(); } finally { songs.forEach((s, i) => Object.assign(s, arted[i])); } }); expectNoDiagnostics(artifact); }); it("comes back to the track and the second the last visit left", async () => { const { artifact } = await captureArtifact(async () => { const left = songs[3]!; // not the first: a restore that picked wrongly would show // What the previous page left in storage. The key is written by the player's own // store (player/session.ts) and read back once the index has settled — the bar // is where that either appears or does not. localStorage.setItem( "hackermusic.player.session.v1", JSON.stringify({ server: "https://nav.example.com\u0000admin", ids: songs.map((s) => s.id), at: left.id, atOffset: 37, }), ); const stream = await bootConnected(); await waitFor(() => expect(player().peekCurrent()?.id).toBe(left.id)); expect(player().peekState()).toBe("idle"); expect(elapsed()).toBe("0:37"); expect(bar()!.querySelector(".pb-title")!.textContent).toBe(left.title); expect(bar()!.querySelector(".pb-count")!.textContent).toBe(String(songs.length)); // the row it came back on says so, which is the list agreeing with the bar // the list agrees with the bar about which row this is expect(rowByTitle(left.title!).classList.contains("lib-row--playing")).toBe(true); // Nothing was heard or asked for to get here: the page came back, it did not // start playing. Audio starts on a gesture and a reload is not one. expect(FakeAudioContext.instances).toHaveLength(0); expect(urlsFor(stream, left.id)).toHaveLength(0); // …and the space bar picks the thread up at the second the slider is showing. fireEvent.keyDown(window, { key: " " }); await waitFor(() => expect(player().peekState()).toBe("playing")); expect(audio().sourceFor(left.id)!.startOffset).toBe(37); }); expectNoDiagnostics(artifact); }); it("comes back to nothing when the stored session belongs to another server", async () => { const { artifact } = await captureArtifact(async () => { localStorage.setItem( "hackermusic.player.session.v1", JSON.stringify({ server: "https://somewhere.else\u0000admin", ids: songs.map((s) => s.id), at: songs[3]!.id, atOffset: 37, }), ); await bootConnected(); // The ids are another server's; putting them on this one's bar would be a track // list from a different library wearing this one's titles. await waitFor(() => expect(library().status()).toBe("ready")); expect(player().peekCurrent()).toBeNull(); // The bar is the waiting one — the row with nothing behind it — rather than a track list from a // different library wearing this one's titles. expect(bar()!.querySelector(".pb-title-row")).toBeNull(); expect(bar()!.querySelector(".pb-wave")!.hasAttribute("data-idle")).toBe(true); }); expectNoDiagnostics(artifact); }); /* ------------------------ the detected regions ------------------------ */ /** * The detector's half of the bar, with the worker faked (`src/test/worker.ts`) rather than * the detector: what is being watched here is what the chip is able to say and when, and the * answers it is built from are the search's own — the algorithm has detect.test.ts, and the * message that crosses has analyze.test.ts. */ const chipText = () => loopChip()?.textContent ?? null; const chipTone = () => loopChip()?.dataset.tone ?? null; const press = (key: string, target: HTMLElement | Document = document.body) => fireEvent.keyDown(target as Element, { key }); /** * Answer every analysis the held worker is sitting on, with the same regions. * * The bar asks about the track playing *and* the one prefetched behind it, so a test that * answered one request would be guessing which question it was answering — and answering the * wrong one is exactly the bug the token exists to prevent. That bug is caught in * analyze.test.ts, where the two questions are asked in a known order; here the point is what * the chip can say, so both get the same news. */ const answer = (worker: FakeWorker, reply: Omit): void => { for (const request of worker.requests) worker.reply({ ...reply, token: request.token }); }; /** A track with a loop in it: 8 s of head, then a 20 s body twice. */ const LOOPY = loopTrack({ introSec: 8, periodSec: 20, repeats: 2 }); const LOOP_SECONDS = { "al-1-s0": LOOPY.seconds }; it("c arms the loop that is actually in the bytes, and the chip counts them", async () => { const { artifact } = await captureArtifact(async () => { vi.stubGlobal("Worker", FakeWorker); await bootPlaying("Track 1", { decodedSeconds: LOOP_SECONDS, waveformFor: () => LOOPY.samples, }); await waitFor(() => expect(FakeWorker.instances.length).toBe(1)); const worker = FakeWorker.instances[0]!; // Asked without being asked for: the bytes landed and the search went out, on the other // thread, before anybody touched a key. await waitFor(() => expect(worker.requests.length).toBeGreaterThan(0)); expect(worker.requests[0]!.values).toBeInstanceOf(Float32Array); // An answer is not a decision. The track is playing, the loop has been found, and the // transport has not been touched. await waitFor(() => expect(player().peekLoopAnalysis()?.status).toBe("found")); expect(player().peekLoop()).toBeNull(); expect(chipText()).toBeNull(); // Stand under it and ask. One candidate, so the chip says which of one it armed — the // count is the whole point of the chip in this state: it is the readout that says the // next press has somewhere to go. player().seek(12); expect(press("c")).toBe(false); // the transport took it await waitFor(() => expect(loopChip()).toBeTruthy()); expect(chipText()).toBe("A–B 1/1"); // The machine's ink, not the listener's: this region is a claim about the file, and the bar // says so until a hand marks the same seconds over it. expect(chipTone()).toBe("detected"); expect(markRegion()!.dataset.origin).toBe("detected"); // The same word on the bars, because they are the same span: a region wearing the listener's gold // in the bars while its edges said the machine vouched for it would be two statements about one // region. Awaited, because the fold and the arming are independent of each other. await waitFor(() => expect(markRegion()!.dataset.origin).toBe("detected")); const region = player().peekLoop()!; // The edges the file has, not the ones the test named. The detector trims a candidate to the // stretch its two copies actually agree over, so where that begins is a property of the // material rather than of the fixture's spec: the length is the assertion, and the place is // allowed a couple of seconds either side of the seam. expect(region.end - region.start).toBeCloseTo(20, 0); expect(region.start).toBeGreaterThan(5); expect(region.start).toBeLessThan(10); // Click is the third `m`: the same command, and the candidate machine goes with it. fireEvent.click(loopChip()!); await waitFor(() => expect(player().peekLoop()).toBeNull()); expect(loopChip()).toBeNull(); expect(player().peekLoopSuggestion()).toBeNull(); }); expectNoDiagnostics(artifact); }); it("the tempo sits above the title and pulses on the beat", async () => { const { artifact } = await captureArtifact(async () => { FakeWorker.auto = false; // hold the wire: the number may not appear before the answer does vi.stubGlobal("Worker", FakeWorker); await bootPlaying("Track 1", { decodedSeconds: LOOP_SECONDS, waveformFor: () => LOOPY.samples, }); await waitFor(() => expect(FakeWorker.instances.length).toBe(1)); const worker = FakeWorker.instances[0]!; await waitFor(() => expect(worker.requests.length).toBeGreaterThan(0)); // Nothing has been said about tempo, and the bar does not guess one from metadata. expect(document.querySelector(".pb-bpm")).toBeNull(); // The stats the real search makes for these bytes, with the tempo the bar is being shown, // and the real grid to arm the pulse on. const found = detect(LOOPY.samples, LOOPY.sampleRate); expect(found.stats).toBeTruthy(); expect(found.beats?.length).toBeGreaterThan(4); answer(worker, { candidates: [], not: "no-repeat", stats: { ...found.stats!, bpm: 96, beatAt: 0.5 }, beats: found.beats, }); const dot = await waitFor(() => { const el = document.querySelector(".pb-bpm"); expect(el?.textContent).toBe("96"); return el!; }); // One cycle is one mean beat: 60/96, written to the four decimals the memo keeps. The phase // is not a style any more — the component writes the animation's `currentTime` from the // playhead each tick, which is invisible under jsdom (no WAAPI) and asserted in // detect.test.ts at the seam the writes read from: the beat times cross with the verdict. expect(dot.dataset.beat).toBe("on"); // The phase is a number the component paints from the audio clock every frame — 0 on a // transient, 1 on the next — and the CSS is pure arithmetic on it. jsdom paints nothing, // but the paint is still observable, and it is deterministic enough to assert against a // playhead placed by hand. await waitFor(() => expect(dot.style.getPropertyValue("--pb-phase")).not.toBe("")); const painted = () => Number.parseFloat(dot.style.getPropertyValue("--pb-phase")); expect(painted()).toBeGreaterThanOrEqual(0); expect(painted()).toBeLessThanOrEqual(1); // The cover breathes on the very same number. One frame, one reading of the audio clock, both // wearers — which is the only reason an eight-pixel swell on a 44px tile is bearable: it cannot // swell half a beat away from the tempo the bar is reporting two inches away. const art = document.querySelector(".pb-art")!; expect(art.dataset.beat).toBe("on"); expect(art.style.getPropertyValue("--pb-phase")).toBe(dot.style.getPropertyValue("--pb-phase")); // Put the playhead exactly between two grid transients and the phase says so: this is // the contract the two-clock design could only keep when the corrections landed, which // is exactly what it was flaky about. Here there is nothing to land. const b5 = found.beats![5]!; const b6 = found.beats![6]!; player().seek(b5 + (b6 - b5) / 2); await waitFor(() => expect(Math.abs(painted() - 0.5)).toBeLessThan(0.02)); // And paused it freezes with the music — not "frozen until the next correction lands" // but frozen because the phase *is* the playhead, and a playhead that does not move has // exactly one phase. Frames keep painting; they keep painting the same number. player().pause(); await waitFor(() => expect(Math.abs(painted() - 0.5)).toBeLessThan(0.02)); const frozen = painted(); await new Promise((r) => setTimeout(r, 80)); // several frames of wall-clock time expect(painted()).toBe(frozen); // The number freezes with the music and that is honest; the cover stops wearing the beat at all, // because a frozen phase there is a picture stuck eight pixels too big beside a paused mark — // the one state in the bar that must not look like it is still keeping time. expect(art.dataset.beat).toBeUndefined(); }); expectNoDiagnostics(artifact); }); /** * The readout under the octave, and the one thing in it that is allowed to move. * * The tempo is a fact about what the listener is hearing, so at `2×` a track the analysis measured * at 96 is at 192 — while the pulse keeps its own interval, because the interval is a distance * along the file and the file did not change. That is the exact place where the "consistency" fix * is wrong: scale the readout *and* the phase together, as every instinct in the file says to, and * the flash is half a beat off the sound at every octave. Both halves are therefore pinned against * the same presses, from independent sources — and deliberately on a grid-less answer, since a * track that came back with beat times takes its phase from those and leaves the mean period as * the fallback the octave could actually reach. */ it("under a speed change the tempo says what is being heard, and the pulse keeps its own interval", async () => { const { artifact } = await captureArtifact(async () => { FakeWorker.auto = false; vi.stubGlobal("Worker", FakeWorker); await bootPlaying("Track 1", { decodedSeconds: LOOP_SECONDS, waveformFor: () => LOOPY.samples, }); // The detect worker by name rather than `instances[0]`: the beat tracker builds its own worker // off the same stubbed global a few microseconds later, and which of the two is number one is // a race a test has no business winning. This one is about the search's answer. await waitFor(() => expect(FakeWorker.instances.some((w) => String(w.url).includes("detect.worker"))).toBe(true), ); const worker = FakeWorker.instances.find((w) => String(w.url).includes("detect.worker"))!; await waitFor(() => expect(worker.requests.length).toBeGreaterThan(0)); // The stats the real search makes for these bytes, with the tempo the bar is being shown — and // no `beats`: a track answered on the frame grid has no times, so its phase runs the mean // period, which is the one number a speed change could reach. With a grid the phase walks the // transients and the period is never read, and this test would assert nothing. const found = detect(LOOPY.samples, LOOPY.sampleRate); answer(worker, { candidates: [], not: "no-repeat", stats: { ...found.stats!, bpm: 96, beatAt: 0 }, }); const tempo = () => document.querySelector(".pb-bpm")?.textContent ?? null; const mark = () => document.querySelector(".pb-varispeed")?.textContent ?? null; const phase = () => Number.parseFloat( document.querySelector(".pb-bpm")!.style.getPropertyValue("--pb-phase"), ); /** * The phase as the file says it, from an outside source: the playhead over one beat *of the * record*, clamped the way the paint clamps it. Every phase assertion below is measured against * this rather than against the previous phase, because the playhead legitimately moves under * these presses — a handover walks it 80ms of the file forward, at the rate the outgoing node * was running at — and "the phase did not change" would be both false and the wrong claim. The * claim is that the interval it is measured against did not change, and a bar that scaled the * period along with the readout (the tempting consistency fix) lands half a beat away from * here. */ const honest = () => Math.min(1, player().peekLivePosition() / (60 / 96)); await waitFor(() => expect(tempo()).toBe("96")); // at the record's own speed there is nothing to explain, so nothing is said expect(mark()).toBeNull(); // Inside the first beat, deliberately: the grid-less fallback clamps rather than wrapping, so // past 0.625 s the phase is a constant 1 and the assertion would be comparing two 1s. Four // presses travel the playhead 0.56 s of the file in total — see `honest` — which is why this // starts at 0.2 and not further in. player().seek(0.2); await waitFor(() => expect(Math.abs(phase() - honest())).toBeLessThan(0.01)); fireEvent.keyDown(document.body, { key: "}" }); // The number is the tempo being heard — doubled, and rounded once from the measurement rather // than twice from a rounding. The glyph beside it is the reason, and it belongs to the press // rather than to the file: the sleeve still says 96. await waitFor(() => expect(tempo()).toBe("192")); expect(mark()).toBe("\u00d72"); // ...and the flash is still keeping the beat the grid found, in file seconds: the beats arrive // twice as often in the wall clock on their own, because the clock crosses the file twice as // fast. The wait is several frames of rAF, so this is a claim about what the paint settled on // and not about a value nobody has repainted. expect(document.querySelector(".pb-bpm")?.getAttribute("data-beat")).toBe("on"); await new Promise((r) => setTimeout(r, 60)); expect(Math.abs(phase() - honest())).toBeLessThan(0.01); fireEvent.keyDown(document.body, { key: "{" }); fireEvent.keyDown(document.body, { key: "{" }); await waitFor(() => expect(tempo()).toBe("48")); expect(mark()).toBe("\u00d70.5"); await new Promise((r) => setTimeout(r, 60)); expect(Math.abs(phase() - honest())).toBeLessThan(0.01); // and back through the middle: the number returns to the measurement and the glyph goes away // rather than becoming a `×1` that explains a number that has not moved. fireEvent.keyDown(document.body, { key: "}" }); await waitFor(() => expect(tempo()).toBe("96")); expect(mark()).toBeNull(); // The fine pair, which is the reason the octave is no longer the only speed: 90 % of the record, // a tempo the sleeve has no word for, and the same two rules still holding — the number is what is // heard (96 × 0.9 = 86.4, rounded once) and the flash is still the grid's own interval in file // seconds, because a tempo readout that moved the pulse would be a readout that broke the beat. fireEvent.keyDown(document.body, { key: "<" }); await waitFor(() => expect(player().peekSpeed()).toBe(0.9)); await waitFor(() => expect(tempo()).toBe("86")); expect(mark()).toBe("\u00d70.9"); await new Promise((r) => setTimeout(r, 60)); expect(Math.abs(phase() - honest())).toBeLessThan(0.01); // The analysis outlived the re-arms the presses caused — the answer is about the bytes, and // the bytes did not change — so the tempo never blinked out on the way through the octave. expect(worker.requests.length).toBeGreaterThan(0); }); expectNoDiagnostics(artifact); }); /** * The two readings that must never look alike, at the same pixel, after the same key: *there * is a loop, just not where you are* and *this track does not repeat*. If one of them were * the chip's silence, the feature would read as broken on exactly the music it was built * for — and the way to show they are different is to show both, in one test, side by side. */ it("the chip says 'elsewhere' and 'no loop' in different voices", async () => { const { artifact } = await captureArtifact(async () => { FakeWorker.auto = false; // hold the wire: the key is pressed while the search is out there vi.stubGlobal("Worker", FakeWorker); await bootPlaying("Track 1", { decodedSeconds: LOOP_SECONDS, waveformFor: () => LOOPY.samples, }); await waitFor(() => expect(FakeWorker.instances.length).toBe(1)); const worker = FakeWorker.instances[0]!; await waitFor(() => expect(worker.requests.length).toBeGreaterThan(0)); player().seek(3); // in the head, under nothing the search will find expect(press("c")).toBe(false); // The answer has not come, and the chip says that rather than guessing: an empty chip // after a key press is a key that appears not to work. await waitFor(() => expect(chipText()).toBe("A–B …")); expect(chipTone()).toBe("quiet"); expect(player().peekLoop()).toBeNull(); // It comes, and it is not under the playhead: a muted gold, with the place in it. answer(worker, { candidates: [{ start: 10, end: 25, period: 15, r: 0.99 }] }); await waitFor(() => expect(chipText()).toBe("A–B elsewhere")); expect(chipTone()).toBe("suggest"); expect(player().peekLoop()).toBeNull(); // held up, not armed expect(player().peekLoopSuggestion()!.missesAnchor).toBe(true); // The press after that is the listener saying yes to what was held in front of them — and the // ink they get for it is the machine's blue, because the boundaries are still the machine's. expect(press("c")).toBe(false); await waitFor(() => expect(chipTone()).toBe("detected")); expect(player().peekLoop()).toEqual({ start: 10, end: 25 }); }); expectNoDiagnostics(artifact); }); /** * The two ink-colours and the two arrow keys, in one sitting. * * The colour is the cheap half and it is not decoration: a region the app measured and a region * somebody placed are the same two edges on the same eleven-pixel track, and the listener has to be * able to tell, at a glance and without reading a chip, which of them they are looking at — because * one of them is evidence and the other is a decision. The arrows are the expensive half, and the * test is that they answer to the first and not the second: growing a listener's own marks into a * machine's guess would be the feature arguing with the only evidence a person actually gave it. */ it("the detector's region is drawn in blue, grown and shrunk by the arrows, and the hand's is neither", async () => { const { artifact } = await captureArtifact(async () => { FakeWorker.auto = false; vi.stubGlobal("Worker", FakeWorker); await bootPlaying("Track 1", { decodedSeconds: LOOP_SECONDS, waveformFor: () => LOOPY.samples, }); await waitFor(() => expect(FakeWorker.instances.length).toBe(1)); const worker = FakeWorker.instances[0]!; await waitFor(() => expect(worker.requests.length).toBeGreaterThan(0)); // Three claims about the same passage: the tight one, one that reaches back into the head, and // one that runs on past the seam. Standing inside all three, `c` takes the tightest. answer(worker, { candidates: [ { start: 10, end: 25, period: 15, r: 0.99 }, { start: 8, end: 25, period: 17, r: 0.97 }, { start: 10, end: 30, period: 20, r: 0.96 }, ], }); await waitFor(() => expect(player().peekLoopAnalysis()?.status).toBe("found")); player().seek(12); expect(press("c")).toBe(false); await waitFor(() => expect(player().peekLoop()).toEqual({ start: 10, end: 25 })); expect(markRegion()!.dataset.origin).toBe("detected"); // Longer — the next claim up that still covers the loop being heard, not another two seconds // of boundary stretched into the noise. expect(press("ArrowUp")).toBe(false); // the key's own return value is the transport's, not the loop's await waitFor(() => expect(player().peekLoop()).toEqual({ start: 8, end: 25 })); expect(markRegion()!.dataset.origin).toBe("detected"); // Nothing longer covers this one, so the key does nothing at all rather than inventing a shape. expect(press("ArrowUp")).toBe(false); expect(player().peekLoop()).toEqual({ start: 8, end: 25 }); // And back down, to the tighter claim about the same passage. expect(press("ArrowDown")).toBe(false); await waitFor(() => expect(player().peekLoop()).toEqual({ start: 10, end: 25 })); // Marked by hand, the same two edges are a different kind of thing: the gold comes back, and // the arrows stop answering — which is also the case where the library gets its cursor back. player().setLoop({ start: 10, end: 25 }); await waitFor(() => expect(markRegion()!.dataset.origin).toBe("hand")); expect(press("ArrowUp")).toBe(false); expect(player().peekLoop()).toEqual({ start: 10, end: 25 }); }); expectNoDiagnostics(artifact); }); it("`C` walks the candidates along the track, one press each", async () => { const { artifact } = await captureArtifact(async () => { FakeWorker.auto = false; vi.stubGlobal("Worker", FakeWorker); await bootPlaying("Track 1", { decodedSeconds: LOOP_SECONDS, waveformFor: () => LOOPY.samples, }); await waitFor(() => expect(FakeWorker.instances.length).toBe(1)); const worker = FakeWorker.instances[0]!; await waitFor(() => expect(worker.requests.length).toBeGreaterThan(0)); // Deliberately answered out of order: the walk is along the timeline, so the first press lands // at the earliest region whatever the search's ranking had said about them. answer(worker, { candidates: [ { start: 40, end: 46, period: 6, r: 0.99 }, // inside the 48 s of bytes on the bar { start: 12, end: 27, period: 15, r: 0.95 }, { start: 26, end: 41, period: 15, r: 0.97 }, ], }); await waitFor(() => expect(player().peekLoopAnalysis()?.status).toBe("found")); player().seek(3); expect(press("C")).toBe(false); await waitFor(() => expect(player().peekLoop()).toEqual({ start: 12, end: 27 })); expect(chipText()).toBe("A–B 1/3"); expect(press("C")).toBe(false); await waitFor(() => expect(player().peekLoop()).toEqual({ start: 26, end: 41 })); expect(chipText()).toBe("A–B 2/3"); expect(press("C")).toBe(false); await waitFor(() => expect(player().peekLoop()).toEqual({ start: 40, end: 46 })); // and round the other way, because the list is a tour and a tour has no exit expect(press("C")).toBe(false); await waitFor(() => expect(player().peekLoop()).toEqual({ start: 12, end: 27 })); }); expectNoDiagnostics(artifact); }); it("← / → take the loop to the next place along the track", async () => { const { artifact } = await captureArtifact(async () => { FakeWorker.auto = false; vi.stubGlobal("Worker", FakeWorker); await bootPlaying("Track 1", { decodedSeconds: LOOP_SECONDS, waveformFor: () => LOOPY.samples, }); await waitFor(() => expect(FakeWorker.instances.length).toBe(1)); const worker = FakeWorker.instances[0]!; await waitFor(() => expect(worker.requests.length).toBeGreaterThan(0)); // One candidate per other place, with the places between them empty: the bar is 48 seconds of // bytes, so a place is eight seconds, and the walk has to skip the empty ones rather than // reporting a move to a stretch of song that has no loop in it. answer(worker, { candidates: [ { start: 1, end: 6, period: 5, r: 0.98 }, { start: 20, end: 26, period: 6, r: 0.99 }, { start: 34, end: 40, period: 6, r: 0.97 }, ], }); await waitFor(() => expect(player().peekLoopAnalysis()?.status).toBe("found")); player().seek(3); expect(press("c")).toBe(false); await waitFor(() => expect(player().peekLoop()).toEqual({ start: 1, end: 6 })); expect(press("ArrowRight")).toBe(false); await waitFor(() => expect(player().peekLoop()).toEqual({ start: 20, end: 26 })); expect(markRegion()!.dataset.origin).toBe("detected"); expect(press("ArrowRight")).toBe(false); await waitFor(() => expect(player().peekLoop()).toEqual({ start: 34, end: 40 })); expect(press("ArrowLeft")).toBe(false); await waitFor(() => expect(player().peekLoop()).toEqual({ start: 20, end: 26 })); // On a region the listener marked themselves, too: these two keys navigate the detector's list // rather than resize anybody's boundaries, which is the distinction that keeps `↑`/`↓` away from // gold. Nothing was asked of the marks except to be replaced by the loop the key pointed at. player().setLoop({ start: 4, end: 8 }); await waitFor(() => expect(markRegion()!.dataset.origin).toBe("hand")); expect(press("ArrowRight")).toBe(false); // from the marks' own place — 0 — the next one with anything in it is the 20-second one await waitFor(() => expect(player().peekLoop()).toEqual({ start: 20, end: 26 })); expect(markRegion()!.dataset.origin).toBe("detected"); }); expectNoDiagnostics(artifact); }); it("a track that does not repeat says so, and does not say it in the colour of a region", async () => { const { artifact } = await captureArtifact(async () => { FakeWorker.auto = false; vi.stubGlobal("Worker", FakeWorker); await bootPlaying("Track 1", { decodedSeconds: LOOP_SECONDS, waveformFor: () => LOOPY.samples, }); await waitFor(() => expect(FakeWorker.instances.length).toBe(1)); const worker = FakeWorker.instances[0]!; await waitFor(() => expect(worker.requests.length).toBeGreaterThan(0)); player().seek(3); press("c"); await waitFor(() => expect(chipText()).toBe("A–B …")); // The through-composed answer: no gold, and the words are the track's, not the search's. answer(worker, { candidates: [], not: "no-repeat" }); await waitFor(() => expect(chipText()).toBe("no loop")); expect(chipTone()).toBe("quiet"); // The weak-evidence answer is the same shape of news and not the same news: something // repeated, and the number was not good enough. Asked about again on the next track, so // the two readouts are on screen one after the other and the words can be compared. expect(chipText()).not.toBe("not sure"); expect(chipText()).not.toBe("not yet"); // The third refusal, from the store's own guard rather than from the search: no bytes, // no timeline, and a readout that says *not yet* rather than *no*. expect(player().peekLoopSuggestion()).toMatchObject({ index: -1 }); player().detectLoop(); await waitFor(() => expect(loopChip()).toBeTruthy()); fireEvent.click(loopChip()!); await waitFor(() => expect(loopChip()).toBeNull()); }); expectNoDiagnostics(artifact); }); /** * The reading that is neither armed nor missing: a candidate under the playhead which the * store would not arm, because it is too short to be a region. It is the chip saying *there * it is* without saying *it is playing*, and the only way to see it is to offer a region the * store's own guard refuses — which is the point: the machine's claim and the store's rule * both get a say, and the bar shows the disagreement instead of hiding it. */ it("a candidate the store will not accept is held up, not armed", async () => { const { artifact } = await captureArtifact(async () => { FakeWorker.auto = false; vi.stubGlobal("Worker", FakeWorker); await bootPlaying("Track 1", { decodedSeconds: LOOP_SECONDS, waveformFor: () => LOOPY.samples, }); await waitFor(() => expect(FakeWorker.instances.length).toBe(1)); const worker = FakeWorker.instances[0]!; await waitFor(() => expect(worker.requests.length).toBeGreaterThan(0)); // Twenty milliseconds of body: under the floor for a region, so `setLoop` refuses it and // the candidate stays where it is — held up, on the anchor, un-armed. player().seek(10); answer(worker, { candidates: [{ start: 10, end: 10.02, period: 0.02, r: 0.99 }] }); press("c"); await waitFor(() => expect(chipText()).toBe("A–B?")); expect(chipTone()).toBe("suggest"); expect(player().peekLoop()).toBeNull(); expect(player().peekLoopSuggestion()).toMatchObject({ index: 0, armed: false }); // Pressing again does not wear it down: the same refusal, the same readout. press("c"); expect(player().peekLoop()).toBeNull(); expect(chipText()).toBe("A–B?"); }); expectNoDiagnostics(artifact); }); /** * `c` is a transport key, which is a claim about two things: it survives a focused button — * where the button's own activation would otherwise double the press — and it survives the * cover overlay, which swallows everything that is not left explicitly on the window. */ it("c reaches the store past a focused button and past the cover", async () => { const { artifact } = await captureArtifact(async () => { FakeWorker.auto = false; vi.stubGlobal("Worker", FakeWorker); await bootPlaying("Track 1", { decodedSeconds: LOOP_SECONDS, waveformFor: () => LOOPY.samples, }); await waitFor(() => expect(FakeWorker.instances.length).toBe(1)); const worker = FakeWorker.instances[0]!; await waitFor(() => expect(worker.requests.length).toBeGreaterThan(0)); player().seek(3); // The repeat button has focus, and `c` is not its activation: the store is asked once // and the button is not clicked, which is the pair the guard below the button check is // there to keep apart. repeatButton().focus(); const before = player().peekRepeat(); expect(press("c", repeatButton())).toBe(false); expect(player().peekRepeat()).toBe(before); await waitFor(() => expect(chipText()).toBe("A–B …")); // The cover goes up over all of it, and `c` still gets through — the chip it drives is on // the bar underneath, and the music is playing, which is why the cover is up. fireEvent.click(artTile()); await waitFor(() => expect(zoom()).toBeTruthy()); expect(press("c", zoom()!)).toBe(false); expect(zoom()).toBeTruthy(); // the overlay did not take the press for itself expect(player().peekState()).toBe("playing"); // and space still belongs to the transport answer(worker, { candidates: [] }); }); expectNoDiagnostics(artifact); }); /** * One chip, and the same story the hand-marked region tells about focus: it sits beside the * repeat button, out of the tab order, and refuses the focus a click would otherwise leave * behind — the app is driven by its keys, and a footer that keeps focus after a press takes * the keyboard away. */ it("the detected chip is the same chip, not a second one", async () => { const { artifact } = await captureArtifact(async () => { FakeWorker.auto = false; vi.stubGlobal("Worker", FakeWorker); await bootPlaying("Track 1", { decodedSeconds: LOOP_SECONDS, waveformFor: () => LOOPY.samples, }); await waitFor(() => expect(FakeWorker.instances.length).toBe(1)); const worker = FakeWorker.instances[0]!; await waitFor(() => expect(worker.requests.length).toBeGreaterThan(0)); player().seek(3); press("C"); // the re-anchoring key, which is the same machine with a new anchor await waitFor(() => expect(chipText()).toBeTruthy()); expect(bar()!.querySelectorAll(".pb-loop")).toHaveLength(1); // one chip, not two expect(loopChip()!.parentElement).toBe(repeatButton().parentElement); expect(loopChip()!.tabIndex).toBe(-1); expect(fireEvent.mouseDown(loopChip()!), "chip").toBe(false); // and the third `m` clears it, which is the same command the click issues answer(worker, { candidates: [{ start: 10, end: 25, period: 15, r: 0.99 }] }); await waitFor(() => expect(chipTone()).toBe("suggest")); // And the hand still outranks the machine: marking a region of their own is the listener // answering the question the chip was asking, so the candidate goes away and what is left // is the plain gold chip with the region they set — one chip, one story, as before. audio().advance(12); press("m"); // A audio().advance(8); press("m"); // B await waitFor(() => expect(player().peekLoop()).toBeTruthy()); expect(player().peekLoopSuggestion()).toBeNull(); expect(chipText()).toBe("A–B"); expect(chipTone()).toBe("region"); // The third `m` is the way out of the region, and the way out of the machine with it. press("m"); await waitFor(() => expect(loopChip()).toBeNull()); expect(player().peekLoopSuggestion()).toBeNull(); }); expectNoDiagnostics(artifact); });