Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188import { 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 { forgetMediaVerdicts } from "../lib/player/media";import { mediaFiles, navidromeFetch, type FakeMediaFile } from "../test/navidrome";import { FakeAudioContext, stubStreamFetch, type StreamFetchStub } from "../test/audio";import { stubResizeObserver } from "../test/env";
/** * Click a track, hear it play — the acceptance test for the whole pipeline, * written against the real app: the row's click handler, the shared player * singleton, the stream URL the Subsonic client builds, and the source node the * engine arms against the audio clock. * * The only substituted pieces are the ones jsdom does not have: a fake * Navidrome for the index and streams (src/test/navidrome.ts, audio.ts) and a * fake AudioContext reachable through the global, which is exactly how the * engine finds the real one in a browser. */
const artists = ["Aphex Twin", "Autechre", "Carpenter Brut"];const shelves: [artist: string, album: string, albumId: string][] = artists.flatMap((artist, a) => [0, 1].map((n) => [artist, `${artist} record ${n}`, `al-${a}-${n}`] as [string, string, string]),);const songs: FakeMediaFile[] = shelves.flatMap(([albumArtist, album, albumId], i) => mediaFiles({ album, albumArtist, albumId }, 3, i),);
let stream: StreamFetchStub;let index: ReturnType<typeof navidromeFetch>;
const trackRows = () => [...document.querySelectorAll<HTMLElement>(".lib-scroll .lib-row--track")];/** Every row the list renders — artist, album and track alike — in list order. The * sticky overlay's copies live outside the scroller, so this is the real list. */const allRows = () => [...document.querySelectorAll<HTMLElement>(".lib-scroll .lib-row")];/** The row the keyboard cursor is on — scoped to the scroller, because the sticky * overlay pins copies of the same headers outside it and those never take marks. */const cursorAt = () => document.querySelector<HTMLElement>(".lib-scroll .lib-row--cursor");const rowTitle = (row: Element) => row.querySelector(".lib-title")?.textContent ?? "";
async function bootConnected() { index = navidromeFetch(songs); stream = stubStreamFetch({ base: index }); vi.stubGlobal("fetch", stream.fetch); vi.stubGlobal("AudioContext", FakeAudioContext); saveConnection({ host: "https://nav.example.com", username: "admin", password: "wordpass" }); render(() => <App />); await waitFor(() => expect(library().status()).toBe("ready"), { timeout: 3000 }); await waitFor(() => expect(trackRows().length).toBeGreaterThan(0));}
const audio = () => FakeAudioContext.instances[FakeAudioContext.instances.length - 1]!;/** * Walk the cursor down with `j` until a row answers `is`. One press per task, * because that is how keys arrive: writes made inside a task stay pending until * the flush, so a synchronous burst would have every press read the same index. */async function walkTo(is: (row: HTMLElement) => boolean): Promise<HTMLElement> { for (let i = 0; i < allRows().length; i++) { fireEvent.keyDown(window, { key: "j" }); await waitFor(() => expect(cursorAt()).not.toBeNull()); if (is(cursorAt()!)) return cursorAt()!; } throw new Error("the walk found no such row");}/** which track a stream request asked for */const trackOf = (url: string) => new URL(url).searchParams.get("id");const urlsFor = (id: string | undefined) => stream.urls.filter((u) => trackOf(u) === id);/** createShare requests the app made, with their query params. */const shareCalls = () => (index as unknown as ReturnType<typeof vi.fn>).mock.calls .map((c: unknown[]) => new URL(String(c[0]))) .filter((u) => u.pathname.endsWith("/createShare"));const shareLine = () => document.querySelector<HTMLElement>(".lib-share");/** jsdom's Blob has no `text()`, so a promised clipboard entry is read the slow way. */const readBlob = (b: Blob) => new Promise<string>((resolve, reject) => { const fr = new FileReader(); fr.onload = () => resolve(String(fr.result)); fr.onerror = () => reject(fr.error); fr.readAsText(b); });
beforeEach(() => { localStorage.clear(); clearConnection(); library().reset(); player().dispose(); forgetMediaVerdicts(); FakeAudioContext.reset(); stubResizeObserver({ width: 1000, height: 0 });});
afterEach(() => { player().dispose(); cleanup(); vi.unstubAllGlobals();});
it("clicking a track fetches its original stream and arms a source", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const rows = trackRows(); const title = rowTitle(rows[1]!);
fireEvent.click(rows[1]!);
await waitFor(() => expect(player().peekState()).toBe("playing")); // the click is the only thing that could have caused this: the id in the // URL is the second track's, and it came from that row expect(urlsFor("al-0-0-s1")).toHaveLength(1); expect(player().peekCurrent()?.title).toBe(title);
const source = audio().sourceFor("al-0-0-s1")!; expect(source.started.length).toBe(1); expect(source.startOffset).toBe(0); // the context came out of suspended — the click is the gesture the autoplay // policy wants, and a player that missed it would be silently mute expect(audio().resumes).toBeGreaterThan(0); expect(audio().state).toBe("running"); }); expectNoDiagnostics(artifact);});
it("a row wears its track's cache as a background grown from the left", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const rows = trackRows();
// nobody has asked for that track's bytes, and the row says nothing about them expect(rows[5]!.querySelector(".lib-cache-fill")).toBeNull();
fireEvent.click(rows[1]!); await waitFor(() => expect(player().peekState()).toBe("playing"));
// the track being heard has its bytes in memory: cached is that same background // worn full, not a hairline and not a crawl — one visual, determinate, at rest const fill = rows[1]!.querySelector<HTMLElement>(".lib-cache-fill"); expect(fill).not.toBeNull(); expect(fill!.style.width).toBe("100%"); // and it is background, not chrome: the row's own text is untouched by it expect(rows[1]!.querySelector(".lib-title")).not.toBeNull(); }); expectNoDiagnostics(artifact);});
it("`r` plays a track at random out of the list on screen", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); // pinned to the top of the range, so "random" has one answer and the test // can say which track it had to be const roll = vi.spyOn(Math, "random").mockReturnValue(0.999); try { fireEvent.keyDown(window, { key: "r" }); await waitFor(() => expect(player().peekState()).toBe("playing"));
// It did not merely start audio: the list was told to move to what it // chose. Waited for, because Solid 2 commits the reveal on the scheduler // rather than synchronously with the keypress — asserting it immediately // reads a write that is still queued, which is a lie the test tells // itself until a slower machine calls it out. await waitFor(() => expect(document.querySelector<HTMLElement>(".lib-scroll")!.scrollTop).toBeGreaterThan(0), ); expect(document.querySelector(".lib-row--playing .lib-title")?.textContent).toBe( player().peekCurrent()?.title, );
const queue = player().queueIds(); expect([...queue].sort()).toEqual(songs.map((s) => s.id).sort()); expect(player().peekCurrent()?.id).toBe(queue[queue.length - 1]);
// The same roll again, and it must not replay the track we are on: the // current one is out of the roll, not rerolled until it misses. const first = player().peekCurrent()?.id; fireEvent.keyDown(window, { key: "r" }); await waitFor(() => expect(player().peekCurrent()?.id).not.toBe(first)); expect(queue).toContain(player().peekCurrent()?.id); // two tracks heard, two streams asked for — and no track asked for twice, // which the prefetch makes a real risk rather than a hypothetical one expect(new Set(stream.urls.map(trackOf)).size).toBeGreaterThanOrEqual(2); expect(stream.urls.length).toBe(new Set(stream.urls).size); } finally { roll.mockRestore(); } }); expectNoDiagnostics(artifact);});
it("`r` picks out of the filter, not the library", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); fireEvent.keyDown(window, { key: "/" }); const box = document.querySelector<HTMLInputElement>(".lib-query-input")!; await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.input(box, { target: { value: "carpenter" } }); await waitFor(() => expect(trackRows().length).toBe(6));
const roll = vi.spyOn(Math, "random").mockReturnValue(0.999); try { // focus is back on the page, which is the only place a hotkey is a hotkey box.blur(); fireEvent.keyDown(window, { key: "r" }); await waitFor(() => expect(player().peekState()).toBe("playing"));
const kept = songs.filter((s) => s.albumArtist === "Carpenter Brut").map((s) => s.id); expect([...player().queueIds()].sort()).toEqual(kept.sort()); // searching for one artist and pressing `r` stays with that artist — it is // not a licence to rescue the user from their own filter expect(kept).toContain(player().peekCurrent()?.id); } finally { roll.mockRestore(); } }); expectNoDiagnostics(artifact);});
it("`r` is a letter while the query box has focus", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); fireEvent.keyDown(window, { key: "/" }); const box = document.querySelector<HTMLInputElement>(".lib-query-input")!; await waitFor(() => expect(document.activeElement).toBe(box));
// The one hotkey with a cost: if the INPUT guard ever slips, typing "rej" // starts streaming a record instead of searching for one, and nothing on // screen explains the music that just began. fireEvent.keyDown(box, { key: "r" }); fireEvent.input(box, { target: { value: "r" } }); expect(player().peekState()).toBe("idle"); expect(stream.urls).toHaveLength(0); }); expectNoDiagnostics(artifact);});
it("`r` drops in; `R` plays the same kind of pick from its first second", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const roll = vi.spyOn(Math, "random").mockReturnValue(0.999999); try { fireEvent.keyDown(window, { key: "r" }); await waitFor(() => expect(player().peekState()).toBe("playing"));
const declared = player().peekCurrent()?.duration ?? 0; expect(declared).toBeGreaterThan(45); // long enough to have a middle const dropped = audio().sourceFor(player().peekCurrent()!.id)!.startOffset!; expect(dropped).toBeGreaterThan(0); expect(dropped).toBeLessThan(declared - 5); // and never so late that it ends on arrival // the source was armed there; a clock that merely reads high while the // source plays from zero would satisfy the position assertion alone expect(player().peekPosition()).toBeCloseTo(dropped, 4);
// shift is the modifier that takes the flourish away: same kind of pick, // heard from its first second const first = player().peekCurrent()?.id; fireEvent.keyDown(window, { key: "R", shiftKey: true }); // Look the second track up by name, and wait for *its* source: the state // still reads playing from the first track, and once a boundary is // pre-armed the newest node may be a successor's. Both mistakes were made // here once, and both passed. let second = ""; await waitFor(() => { second = player().peekCurrent()?.id ?? ""; expect(second).not.toBe(first); expect(audio().sourceFor(second)).toBeTruthy(); }); expect(audio().sourceFor(second)!.startOffset).toBe(0); } finally { roll.mockRestore(); } }); expectNoDiagnostics(artifact);});
it("`Alt+r` queues a whole album and starts it at the top", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const roll = vi.spyOn(Math, "random").mockReturnValue(0.999999); try { // macOS hands Alt+R to the page as "®", which is why the physical key is // consulted for this binding — assert the shape the OS actually sends fireEvent.keyDown(window, { key: "®", code: "KeyR", altKey: true }); await waitFor(() => expect(player().peekState()).toBe("playing"));
const ids = player().queueIds(); expect(ids).toHaveLength(3); // one record, not the list you were looking at expect(player().peekCursor()).toBe(0); // from its top, not from a random track const albums = new Set(songs.filter((s) => ids.includes(s.id)).map((s) => s.albumId)); expect(albums.size).toBe(1); // and it is one album, start to finish } finally { roll.mockRestore(); } }); expectNoDiagnostics(artifact);});
it("marks the row it played — and only that row", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const rows = trackRows(); fireEvent.click(rows[4]!); await waitFor(() => expect(player().peekState()).toBe("playing"));
const marked = [...document.querySelectorAll(".lib-row--playing")]; expect(marked).toHaveLength(1); expect(marked[0]).toBe(rows[4]); }); expectNoDiagnostics(artifact);});
it("the marker follows the clock; neither the clock nor a click moves the list", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const scroller = document.querySelector<HTMLElement>(".lib-scroll")!; scroller.scrollTop = 0; fireEvent.click(trackRows()[0]!); await waitFor(() => expect(player().peekState()).toBe("playing")); expect(document.querySelector(".lib-row--playing")).toBe(trackRows()[0]); // A click names a row the user is already looking at, so revealing it would // be the list moving under their cursor for no reason — and in the grid it // would mean changing the view they chose. Only the random keys jump. expect(scroller.scrollTop).toBe(0);
const scrolled = scroller.scrollTop; audio().sourceFor(player().peekCurrent()!.id)!.finish(); // the buffer ran out on its own await waitFor(() => expect(player().peekCursor()).toBe(1));
// The list says which track is playing, because that is the truth... expect(document.querySelector(".lib-row--playing")).toBe(trackRows()[1]); // ...but the document does not move under the reader. Auto-advance is the // clock's doing, not a choice the user made. expect(scroller.scrollTop).toBe(scrolled); }); expectNoDiagnostics(artifact);});
it("`Alt+r` reveals the record and marks its opening track", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const roll = vi.spyOn(Math, "random").mockReturnValue(0.999999); try { fireEvent.keyDown(window, { key: "r", altKey: true }); await waitFor(() => expect(player().peekState()).toBe("playing"));
// the album's own row is outlined, exactly as a cover click would leave it const outlined = document.querySelector(".lib-row--album.lib-row--hl-top"); expect(outlined).toBeTruthy(); // and the marker sits on the track actually playing, not on the header const marked = document.querySelector(".lib-row--playing")!; expect(marked.querySelector(".lib-title")?.textContent).toBe(player().peekCurrent()?.title); } finally { roll.mockRestore(); } }); expectNoDiagnostics(artifact);});
it("the queue is the list you can see, so `next` follows the filter", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); expect(trackRows().length).toBe(artists.length * 2 * 3);
// filter down to one artist, then play from what is left on screen fireEvent.keyDown(window, { key: "/" }); const box = document.querySelector<HTMLInputElement>(".lib-query-input")!; await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.input(box, { target: { value: "carpenter" } }); await waitFor(() => expect(trackRows().length).toBe(6));
fireEvent.click(trackRows()[0]!); await waitFor(() => expect(player().peekState()).toBe("playing")); // 6 tracks, not the 18 in the library: the queue a click starts is the // queue the typeahead left visible const kept = songs.filter((s) => s.albumArtist === "Carpenter Brut").map((s) => s.id); expect([...player().queueIds()].sort()).toEqual(kept.sort());
const second = player().queueIds()[1]!; player().next(); await waitFor(() => expect(player().peekCursor()).toBe(1)); await waitFor(() => expect(urlsFor(second)).toHaveLength(1)); }); expectNoDiagnostics(artifact);});
it("while a filter is on, `n`/`p` walk the visible rows, not the queue a click minted", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected();
// start a track unfiltered — the queue is the whole library and the playing // track is an Aphex Twin one the needle is about to hide fireEvent.click(trackRows()[0]!); await waitFor(() => expect(player().peekState()).toBe("playing")); expect(player().queueIds().length).toBe(artists.length * 2 * 3);
fireEvent.keyDown(window, { key: "/" }); const box = document.querySelector<HTMLInputElement>(".lib-query-input")!; await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.input(box, { target: { value: "carpenter" } }); await waitFor(() => expect(trackRows().length).toBe(6)); const kept = songs.filter((s) => s.albumArtist === "Carpenter Brut").map((s) => s.id);
// the playing track is not in view: `n` starts navigation at the top fireEvent.keyDown(window, { key: "n" }); await waitFor(() => expect(player().peekCursor()).toBe(0)); expect(player().queueIds()).toHaveLength(6); expect(kept).toContain(player().peekCurrent()!.id); await waitFor(() => expect(player().peekState()).toBe("playing"));
// and now in view, `p` walks back off the top the store's way: it restarts // the first visible row rather than wrapping fireEvent.keyDown(window, { key: "p" }); await waitFor(() => expect(player().peekCursor()).toBe(0)); expect(player().peekCurrent()!.id).toBe(player().queueIds()[0]);
// `n` from there walks to the second visible track fireEvent.keyDown(window, { key: "n" }); await waitFor(() => expect(player().peekCursor()).toBe(1)); expect(player().peekCurrent()!.id).toBe(player().queueIds()[1]!); }); expectNoDiagnostics(artifact);});
it("a filter that hides the playing track makes `p` start at the bottom", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); fireEvent.click(trackRows()[0]!); await waitFor(() => expect(player().peekState()).toBe("playing"));
fireEvent.keyDown(window, { key: "/" }); const box = document.querySelector<HTMLInputElement>(".lib-query-input")!; await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.input(box, { target: { value: "carpenter" } }); await waitFor(() => expect(trackRows().length).toBe(6));
// no *from* to continue, so previous enters at the bottom and walks backwards // from there rather than landing on the top and stranding the walk fireEvent.keyDown(window, { key: "p" }); await waitFor(() => expect(player().peekCursor()).toBe(5)); expect(player().peekCurrent()!.id).toBe(player().queueIds().at(-1)); }); expectNoDiagnostics(artifact);});
it("`n` past the last visible row runs the filtered view out; unfiltered, it runs the queue out", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected();
// unfiltered: `n` is still the store's, walking whatever queue a header click // made — here, a click at the very bottom of the library, so the queue runs out fireEvent.click(trackRows().at(-1)!); await waitFor(() => expect(player().peekState()).toBe("playing")); fireEvent.keyDown(window, { key: "n" }); await waitFor(() => expect(player().peekState()).toBe("idle"));
// filtered: the visible set is the world, so the press past its last row stops // the same way — and does not reach back into anything queued before the filter fireEvent.keyDown(window, { key: "/" }); const box = document.querySelector<HTMLInputElement>(".lib-query-input")!; await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.input(box, { target: { value: "carpenter" } }); await waitFor(() => expect(trackRows().length).toBe(6)); fireEvent.click(trackRows().at(-1)!); await waitFor(() => expect(player().peekState()).toBe("playing")); fireEvent.keyDown(window, { key: "n" }); await waitFor(() => expect(player().peekState()).toBe("idle")); }); expectNoDiagnostics(artifact);});
it("a second click on the same track replays from the bytes it already has", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); fireEvent.click(trackRows()[0]!); await waitFor(() => expect(player().peekState()).toBe("playing")); // decode once; the second play is served from the decoded cache player().stop(); expect(player().peekState()).toBe("idle");
fireEvent.click(trackRows()[0]!); await waitFor(() => expect(player().peekState()).toBe("playing")); const replayed = player().peekCurrent()!.id; expect(urlsFor(replayed)).toHaveLength(1); // one download ... expect(audio().sourcesFor(replayed)).toHaveLength(2); // ... but two fresh source nodes }); expectNoDiagnostics(artifact);});
it("j/k walk the list, Enter plays where the cursor is, n and p walk the player", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const scroller = document.querySelector<HTMLElement>(".lib-scroll")!; const rows = allRows();
// Nothing is picked before the first key, and Enter does not invent a choice: // `j` is the way in, and a stray Enter must not start audio nobody asked for. expect(cursorAt()).toBeNull(); fireEvent.keyDown(window, { key: "Enter" }); expect(player().peekCurrent()).toBeNull();
// The walk lands on the headers rather than stepping over them: an album and // an artist are things you can play, so they are things you can be on. fireEvent.keyDown(window, { key: "j" }); await waitFor(() => expect(cursorAt()).toBe(rows[0])); expect(cursorAt()!.classList.contains("lib-row--artist")).toBe(true); // …and only one row carries it. The sticky overlay pins copies of these very // headers over the list; a cursor drawn on the copy would be two marks for one // choice, and the row you can see would not be the row you picked. expect(document.querySelector(".vlist-sticky .lib-row--cursor")).toBeNull();
fireEvent.keyDown(window, { key: "j" }); await waitFor(() => expect(cursorAt()).toBe(rows[1])); expect(cursorAt()!.classList.contains("lib-row--album")).toBe(true); fireEvent.keyDown(window, { key: "ArrowDown" }); // the same action, other muscle await waitFor(() => expect(cursorAt()).toBe(rows[2])); // the first track at last // Steps this small do not slide the document: the cursor is already on screen, // and a list that scrolls a line per keystroke is unreadable. expect(scroller.scrollTop).toBe(0);
fireEvent.keyDown(window, { key: "Enter" }); await waitFor(() => expect(player().peekState()).toBe("playing")); // the queue is the visible *tracks*, so this is the first of them — the headers // the cursor walked over are not in it expect(player().peekCursor()).toBe(0); expect(rows[2]!.classList.contains("lib-row--playing")).toBe(true); // both marks fit
// Transport moves the player and leaves the reader alone — the distinction the // whole cursor exists to keep. fireEvent.keyDown(window, { key: "n" }); await waitFor(() => expect(player().peekCursor()).toBe(1)); expect(document.querySelector(".lib-row--playing")).toBe(allRows()[3]); expect(cursorAt()).toBe(rows[2]); // the transport moved; the reader did not fireEvent.keyDown(window, { key: "p" }); await waitFor(() => expect(player().peekCursor()).toBe(0)); expect(document.querySelector(".lib-row--playing")).toBe(allRows()[2]); expect(cursorAt()).toBe(rows[2]);
fireEvent.keyDown(window, { key: "k" }); await waitFor(() => expect(cursorAt()).toBe(rows[1]));
// A click picks the cursor up as well: Enter after a click replays the click, // not wherever j had left off. Still no scroll. const firstTrack = trackRows()[0]!; fireEvent.click(firstTrack); await waitFor(() => expect(player().peekCursor()).toBe(0)); await waitFor(() => expect(cursorAt()).toBe(firstTrack));
// ... and walk the whole list, from the top so the walk is its own story and // not a sequel to the click above. `k` clamps at the first row, so holding it // is the way back. Each press is its own task because that is how keys arrive: // writes made inside a task stay pending until the flush, so a synchronous // burst would have every press read the same index and the cursor would walk in // place while the list stayed still. for (let i = 0; i < rows.length; i++) { fireEvent.keyDown(window, { key: "k" }); await waitFor(() => expect(cursorAt()).not.toBeNull()); } expect(cursorAt()).toBe(allRows()[0]);
for (let i = 1; i < rows.length; i++) { fireEvent.keyDown(window, { key: "j" }); const at = i; await waitFor(() => expect(cursorAt()).toBe(allRows()[at])); } // read the rows fresh: the walk scrolled the window, so the elements captured // before it may no longer be the ones on screen await waitFor(() => { const now = allRows(); expect(cursorAt()).toBe(now[now.length - 1]); }); expect(scroller.scrollTop).toBeGreaterThan(0); }); expectNoDiagnostics(artifact);});
/** * The rows between the tracks are not chrome you walk past: an album row and an * artist row name things a player can play, so `Enter` answers with the whole * group under the cursor — the record, or everything that artist has in what is * on screen. That is `Alt+r`'s album semantics (`queue = that album, from its top`) * for a record you pointed at instead of one the dice chose. */it("Enter on an album row plays that record; on an artist row, that artist", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const rows = allRows(); const playing = () => document.querySelector(".lib-row--playing");
// artist, album — the first two presses are both on headers fireEvent.keyDown(window, { key: "j" }); await waitFor(() => expect(cursorAt()).toBe(rows[0])); fireEvent.keyDown(window, { key: "j" }); await waitFor(() => expect(cursorAt()).toBe(rows[1]));
fireEvent.keyDown(window, { key: "Enter" }); await waitFor(() => expect(player().peekState()).toBe("playing"));
// The queue is that record and nothing else: three tracks, one album, from // its top — which is also why `repeat: album` then loops the album you asked // for rather than the list you were looking at. expect([...player().queueIds()]).toEqual(["al-0-0-s0", "al-0-0-s1", "al-0-0-s2"]); expect(player().peekCursor()).toBe(0); // the record is outlined the way a cover click leaves it, and the marker sits // on the track that is playing — not on the header that was pressed expect(rows[1].classList.contains("lib-row--hl-top")).toBe(true); expect(playing()).toBe(allRows()[2]); expect(playing()).not.toBe(rows[1]); // the cursor stays where the reader put it expect(cursorAt()).toBe(rows[1]);
// Up to the artist header, and the same key means the whole artist: six // tracks, both of their records, and no stale outline left over from the // record that was playing a keypress ago. fireEvent.keyDown(window, { key: "k" }); await waitFor(() => expect(cursorAt()).toBe(rows[0])); fireEvent.keyDown(window, { key: "Enter" }); await waitFor(() => expect(player().peekState()).toBe("playing"));
const ids = [...player().queueIds()]; expect(ids).toHaveLength(6); expect(new Set(songs.filter((s) => ids.includes(s.id)).map((s) => s.albumArtist))).toEqual( new Set(["Aphex Twin"]), ); expect(player().peekCursor()).toBe(0); expect(document.querySelectorAll(".lib-row--hl")).toHaveLength(0); }); expectNoDiagnostics(artifact);});
it("a click on a header picks the cursor up, and Enter then plays it", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const album = allRows()[1]!;
// Pointing at a record is not asking to hear it — a track row answers a click // with music because the thing clicked *is* a track. But it is a choice, so it // takes the cursor, and Enter plays what was pointed at. fireEvent.click(album); await waitFor(() => expect(cursorAt()).toBe(album)); expect(player().peekState()).toBe("idle"); expect(stream.urls).toHaveLength(0);
fireEvent.keyDown(window, { key: "Enter" }); await waitFor(() => expect(player().peekState()).toBe("playing")); expect([...player().queueIds()]).toEqual(["al-0-0-s0", "al-0-0-s1", "al-0-0-s2"]); }); expectNoDiagnostics(artifact);});
it("Enter on a header plays that group out of the filter, not the library", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); fireEvent.keyDown(window, { key: "/" }); const box = document.querySelector<HTMLInputElement>(".lib-query-input")!; await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.input(box, { target: { value: "carpenter" } }); await waitFor(() => expect(trackRows().length).toBe(6)); box.blur();
// The first two rows of what the filter left: the artist, then their first // record. `allRows()` now holds only the visible rows, so the group under the // cursor is what is on screen — the same rule that keeps a filtered click from // queueing songs the user has just filtered away. fireEvent.keyDown(window, { key: "j" }); await waitFor(() => expect(cursorAt()).toBe(allRows()[0])); fireEvent.keyDown(window, { key: "Enter" }); await waitFor(() => expect(player().peekState()).toBe("playing"));
const ids = [...player().queueIds()]; expect(ids).toHaveLength(6); expect( songs.filter((s) => ids.includes(s.id)).every((s) => s.albumArtist === "Carpenter Brut"), ).toBe(true); }); expectNoDiagnostics(artifact);});
/** * Enter in the query box has two jobs, and the number of results decides which * one it does. Several results: accept the filter, hand the keyboard back, play * nothing — `/` asked to narrow the list (where the cursor goes instead is the * test below). One result: that track is what the reader has been typing towards, * and the second Enter that would be needed to hear it is a formality, so this * press plays it exactly the way a click on the row would (same queue, same * cursor, same playing mark). */it("Enter in the query box plays the only track the filter leaves", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); fireEvent.keyDown(window, { key: "/" }); const box = document.querySelector<HTMLInputElement>(".lib-query-input")!; await waitFor(() => expect(document.activeElement).toBe(box));
// A shortlist first, to keep the rule honest: with more than one match, Enter // must still be only "get out of the way" — the field cannot become a play // button that starts audio nobody armed. fireEvent.input(box, { target: { value: "carpenter" } }); await waitFor(() => expect(trackRows().length).toBe(6)); fireEvent.keyDown(box, { key: "Enter" }); await waitFor(() => expect(document.activeElement).not.toBe(box)); expect(player().peekState()).toBe("idle"); expect(stream.urls).toHaveLength(0);
// Narrowing the needle to something exactly one song answers is the moment the // search is over. (`/` would have cleared the old needle; the field is typed from // here, which is what the reader does next either way.) fireEvent.keyDown(window, { key: "/" }); await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.input(box, { target: { value: "carpenter brut record 1 track 6" } }); await waitFor(() => expect(trackRows().length).toBe(1)); expect(rowTitle(trackRows()[0]!)).toBe("Track 6");
fireEvent.keyDown(box, { key: "Enter" }); // Both consequences of the one press: the caret is gone, the song is on. await waitFor(() => expect(document.activeElement).not.toBe(box)); expect(box.value).toBe("carpenter brut record 1 track 6"); // the filter stays await waitFor(() => expect(player().peekState()).toBe("playing")); // The filter is the queue: one result, so `n` runs out rather than walking into // the songs the reader just filtered away. expect([...player().queueIds()]).toEqual(["al-2-1-s5"]); expect(player().peekCurrent()?.id).toBe("al-2-1-s5"); expect(urlsFor("al-2-1-s5")).toHaveLength(1); // And the list says so, with both marks a click would have left. expect(cursorAt()).toBe(trackRows()[0]); expect(document.querySelector(".lib-scroll .lib-row--playing")).toBe(trackRows()[0]); }); expectNoDiagnostics(artifact);});
/** * The same press, one search later, when the song it names is the song already * playing. The reader has not asked to hear it again from its first second — they * have finished looking — so the accept marks the row and gets out of the way * instead of re-arming the track: no new download, no new source node, no playhead * snapped back to zero. */it("Enter on the only track does not restart the track that is already playing", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const box = document.querySelector<HTMLInputElement>(".lib-query-input")!; fireEvent.keyDown(window, { key: "/" }); await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.input(box, { target: { value: "carpenter brut record 1 track 6" } }); await waitFor(() => expect(trackRows().length).toBe(1));
fireEvent.keyDown(box, { key: "Enter" }); await waitFor(() => expect(player().peekState()).toBe("playing")); const id = player().peekCurrent()!.id; expect(id).toBe("al-2-1-s5"); expect(urlsFor(id)).toHaveLength(1); expect(audio().sourcesFor(id)).toHaveLength(1);
// Search again, land on the same single song, press Enter: the queue, the bytes // and the source are all left alone. fireEvent.keyDown(window, { key: "/" }); await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.input(box, { target: { value: "carpenter brut record 1 track 6" } }); await waitFor(() => expect(trackRows().length).toBe(1)); fireEvent.keyDown(box, { key: "Enter" }); await waitFor(() => expect(document.activeElement).not.toBe(box));
expect(player().peekState()).toBe("playing"); expect(player().peekCurrent()?.id).toBe(id); expect(urlsFor(id)).toHaveLength(1); // not fetched again ... expect(audio().sourcesFor(id)).toHaveLength(1); // ... and not armed again // The accept still did its other job: the keyboard is back with the list, on the // row the search left. expect(cursorAt()).toBe(trackRows()[0]);
// Paused is not underway, so the press there is still a play: a song frozen at // some second is not the answer to "play this", and a silent Enter is a key that // did nothing. The source is armed again, from the top. player().pause(); await waitFor(() => expect(player().peekState()).toBe("paused"));
fireEvent.keyDown(window, { key: "/" }); await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.input(box, { target: { value: "carpenter brut record 1 track 6" } }); await waitFor(() => expect(trackRows().length).toBe(1)); fireEvent.keyDown(box, { key: "Enter" }); await waitFor(() => expect(player().peekState()).toBe("playing")); expect(audio().sourcesFor(id)).toHaveLength(2); expect(urlsFor(id)).toHaveLength(1); // the bytes are still not fetched twice }); expectNoDiagnostics(artifact);});
/** * Coming out of a search, the library that opens up is a thousand rows with no hint * of where the reader had been. The one place worth landing is the track they are * hearing — which is what the bar's own name answers with when it is clicked, and the * same answer `/` gives here: cursor on it, list scrolled to it. */it("clearing the filter lands the cursor on the track being heard, not on row 0", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); // Something playing, and playing at the far end of the library: the row a plain // reset would have left off the screen. const heard = library().songs()[17]!; player().playSongs(library().songs(), 17); await waitFor(() => expect(player().peekCurrent()?.id).toBe(heard.id));
const box = document.querySelector<HTMLInputElement>(".lib-query-input")!; fireEvent.keyDown(window, { key: "/" }); await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.input(box, { target: { value: "autechre" } }); await waitFor(() => expect(trackRows().length).toBe(6)); fireEvent.keyDown(box, { key: "Enter" }); await waitFor(() => expect(document.activeElement).not.toBe(box)); // The filter is hiding the thing being heard, so no row on screen claims it expect(document.querySelector(".lib-scroll .lib-row--playing")).toBeNull();
// `/` clears the needle, and the whole list comes back with the cursor on the row // the reader was listening to const scroller = document.querySelector<HTMLElement>(".lib-scroll")!; fireEvent.keyDown(window, { key: "/" }); await waitFor(() => expect(document.activeElement).toBe(box)); await waitFor(() => expect(trackRows().length).toBeGreaterThan(6));
const at = cursorAt(); expect(at).not.toBeNull(); expect(at!.classList.contains("lib-row--track")).toBe(true); expect(at!.classList.contains("lib-row--playing")).toBe(true); // ...and the window went to it rather than sitting at the top of the library await waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(0));
// The keys carry on from there: `k` steps to the row above the one being heard, // not to the top of a list the reader never asked to be at fireEvent.keyDown(window, { key: "k" }); await waitFor(() => expect(cursorAt()).not.toBe(at)); expect(cursorAt()!.classList.contains("lib-row--playing")).toBe(false); }); expectNoDiagnostics(artifact);});
/** * The other half of accepting a filter: a search that leaves a shortlist hands the * keyboard back with *nothing picked*, which means the keys the reader now hold * (`j`/`k`, `Enter`, `s`) start from nowhere — and `k` from nowhere wraps to the * bottom of the list, which is the opposite of where they were looking. So Enter * takes up the cursor on the top row and stops there: navigation is armed, music * is still nobody's. * * The top *row*, header included, because that is the row `j` arrives at from an * unset cursor and the row the reader can see at the top of the list. A cursor on * an artist header is a real choice, not a placeholder: `Enter` there plays that * artist, which is a thing this app does on purpose. */it("Enter in the query box arms the cursor at the top row, and plays nothing", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); fireEvent.keyDown(window, { key: "/" }); const box = document.querySelector<HTMLInputElement>(".lib-query-input")!; await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.input(box, { target: { value: "carpenter" } }); await waitFor(() => expect(trackRows().length).toBe(6));
expect(cursorAt()).toBeNull(); // nothing picked yet: the reader has only searched fireEvent.keyDown(box, { key: "Enter" }); await waitFor(() => expect(document.activeElement).not.toBe(box)); await waitFor(() => expect(cursorAt()).toBe(allRows()[0])); expect(cursorAt()!.classList.contains("lib-row--artist")).toBe(true); // the top row, as `j` would land it // and accepting a filter is still not a play expect(player().peekState()).toBe("idle"); expect(stream.urls).toHaveLength(0);
// Proof the cursor is genuinely *on* row 0 rather than merely unset: from unset, // `k` wraps to the bottom of the list; from the top row it clamps in place. fireEvent.keyDown(window, { key: "k" }); await waitFor(() => expect(cursorAt()).toBe(allRows()[0])); fireEvent.keyDown(window, { key: "j" }); await waitFor(() => expect(cursorAt()).toBe(allRows()[1]));
// A pick the reader made themselves outranks ours: handing the keyboard back with // Enter, when nothing has been typed since the pick, must not yank the cursor back // to the top. The caret goes in by click rather than `/` — a second `/` clears the // needle, and the row set the cursor was chosen from changes under it (what `/` // does to the needle is the command line's own test). const picked = cursorAt()!; box.focus(); await waitFor(() => expect(document.activeElement).toBe(box)); fireEvent.keyDown(box, { key: "Enter" }); await waitFor(() => expect(document.activeElement).not.toBe(box)); expect(cursorAt()).toBe(picked); }); expectNoDiagnostics(artifact);});
it("s shares the track under the cursor, on the clipboard, expiring tomorrow", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const written: string[] = []; Object.defineProperty(navigator, "clipboard", { value: { writeText: async (t: string) => written.push(t) }, configurable: true, }); try { // With nothing picked and nothing playing there is no "the track I mean", // and inventing one would share some stranger's song. It says so, and does // not even ask the server. fireEvent.keyDown(window, { key: "s" }); await waitFor(() => expect(shareLine()?.textContent).toContain("nothing to share")); expect(shareLine()!.dataset.bad).toBe("true"); expect(shareCalls()).toHaveLength(0);
// Three presses to reach a song — artist header, album header, then the // first track — because the rows in between are selectable too. const cursor = await walkTo((el) => el.classList.contains("lib-row--track")); expect(rowTitle(cursor)).toBe(songs[0]!.title);
const before = Date.now(); // Held down, the key repeats. One request per intended share, not one per // frame of autorepeat — each would mint another share on the server. fireEvent.keyDown(window, { key: "s" }); fireEvent.keyDown(window, { key: "s" }); await waitFor(() => expect(written).toHaveLength(1)); expect(shareCalls()).toHaveLength(1);
const params = shareCalls()[0]!.searchParams; // The share page's headline is artist and title — the two fields a stranger // scanning a link actually wants, and the server substitutes its own guess // for the contents when this is empty. const shared = songs.find((x) => x.title === rowTitle(cursor))!; expect(params.get("id")).toBe(shared.id); expect(params.get("description")).toBe( `${shared.albumArtist ?? shared.artist} \u2014 ${shared.title}`, ); // A day, not Navidrome's stored-forever default: the server keeps no expiry // at all when the param is missing, and a public link to a file that never // dies is a liability nobody chose. const expires = Date.parse(params.get("expires")!); expect(expires - before).toBeGreaterThanOrEqual(23 * 3600e3); expect(expires - before).toBeLessThanOrEqual(25 * 3600e3);
// The link is the server's root-relative path resolved against the host we // are talking to — pasted into a chat, /share/tk1 would be a dead end. expect(written[0]).toBe(`https://nav.example.com/share/tk1`); await waitFor(() => expect(shareLine()?.textContent).toContain("shared")); expect(shareLine()!.textContent).toContain("https://nav.example.com/share/tk1");
// The line is transient chrome: the next key of any kind clears it — except the // one that says the clipboard refused, which is kept below. fireEvent.keyDown(window, { key: "j" }); await waitFor(() => expect(shareLine()).toBeNull()); } finally { delete (navigator as unknown as { clipboard?: unknown }).clipboard; } }); expectNoDiagnostics(artifact);});
/** * The copy has to be *asked for* while the keypress still counts as a user gesture, and * the share has to be asked for first — so the two are issued together and only the * write is awaited later. `ClipboardItem` taking a promise as its entry value is what * makes that order possible, and it is the difference between a copy that works over a * tailnet and one that works only on localhost. */it("s claims the clipboard while the share request is still in flight", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); const writes: Record<string, Promise<Blob>>[] = []; class FakeClipboardItem { entries: Record<string, Promise<Blob>>; constructor(entries: Record<string, Promise<Blob>>) { this.entries = entries; } } vi.stubGlobal("ClipboardItem", FakeClipboardItem); Object.defineProperty(navigator, "clipboard", { value: { // Not async: what this test measures is that the call itself lands in the // caller's synchronous run, which is what the activation gate looks at. write: (items: FakeClipboardItem[]) => { writes.push(items[0]!.entries); return Promise.resolve(); }, // The fallback must not be what this test passes on: if the late write is // reached, the claim below is being skipped and the copy is back to depending // on an activation the round trip has already spent. writeText: async () => { throw new Error("writeText was reached, so the write was not claimed"); }, }, configurable: true, }); try { await walkTo((el) => el.classList.contains("lib-row--track"));
fireEvent.keyDown(window, { key: "s" }); // Asserted before anything is awaited: the write is already in the browser's // hands, and at this point the share response has not been looked at — the // request is still the only reason the URL exists. Reverse the two calls in // share.ts and the write lands after the response, which is after the // keypress's transient activation, and the writeText below is what answers. expect(writes).toHaveLength(1);
await waitFor(() => expect(shareLine()?.textContent).toContain("shared")); // ...and the promised entry really carried the link, not an empty blob. It was // handed over unresolved, which is the whole reason the write could be issued // before the answer existed. (FileReader because jsdom's Blob ships no `text()`.) const entry = await writes[0]!["text/plain"]!; expect(await readBlob(entry)).toBe("https://nav.example.com/share/tk1"); // A copy that worked says nothing beyond the link itself. expect(shareLine()!.textContent).not.toContain("Error"); } finally { delete (navigator as unknown as { clipboard?: unknown }).clipboard; } }); expectNoDiagnostics(artifact);});
it("a refused copy is reported in the browser's own words, and the line stays up", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); class FakeClipboardItem { entries: Record<string, Promise<Blob>>; constructor(entries: Record<string, Promise<Blob>>) { this.entries = entries; } } vi.stubGlobal("ClipboardItem", FakeClipboardItem); Object.defineProperty(navigator, "clipboard", { value: { write: async () => { // Chrome's own refusal when DevTools holds the focus, which is the case that // produced `copy failed` with nothing anywhere saying why. throw new DOMException("Document is not focused", "NotAllowedError"); }, }, configurable: true, }); try { await walkTo((el) => el.classList.contains("lib-row--track")); fireEvent.keyDown(window, { key: "s" }); await waitFor(() => expect(shareLine()?.textContent).toContain("shared")); // Name and sentence both reach the line: three refusals reach here with three // different fixes, and collapsing them was the bug. expect(shareLine()!.textContent).toContain("NotAllowedError"); expect(shareLine()!.textContent).toContain("Document is not focused"); // The link is its own element, because it is the thing the user now has to copy // by hand (see `.lib-share-url`, where one click selects it alone). expect(shareLine()!.querySelector(".lib-share-url")!.textContent).toBe( "https://nav.example.com/share/tk1", );
// And the line is not cleared by the next key. The cursor assert is what makes // that an assertion rather than a race: it proves the press was handled, which is // the same handler that clears every other share line. The share is already // minted, the clipboard refused it, and this row is the only copy of the link. const was = cursorAt(); fireEvent.keyDown(window, { key: "j" }); await waitFor(() => expect(cursorAt()).not.toBe(was)); expect(shareLine()).not.toBeNull(); expect(shareLine()!.textContent).toContain("Document is not focused"); } finally { delete (navigator as unknown as { clipboard?: unknown }).clipboard; } }); expectNoDiagnostics(artifact);});
it("a page with no clipboard API at all says so instead of saying copy failed", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); // The insecure-context case: served over http on a LAN address, `navigator.clipboard` // is simply not there, and there is no DOMException to quote. What the line has to // do is name the fix, because the user cannot guess that the app's own URL is the // reason a link on https refused to copy. expect(navigator.clipboard).toBeUndefined(); // The last resort is absent too in jsdom — no `execCommand` — which is what leaves // "needs https" as the only true sentence about it. The next test puts that route // back and expects the copy to work instead. expect(document.execCommand).toBeUndefined(); try { await walkTo((el) => el.classList.contains("lib-row--track")); fireEvent.keyDown(window, { key: "s" }); await waitFor(() => expect(shareLine()?.textContent).toContain("shared")); expect(shareLine()!.textContent).toContain("no clipboard API"); expect(shareLine()!.textContent).toContain("https"); expect(shareLine()!.querySelector(".lib-share-url")!.textContent).toBe( "https://nav.example.com/share/tk1", ); } finally { delete (navigator as unknown as { clipboard?: unknown }).clipboard; } }); expectNoDiagnostics(artifact);});
it("copies the pre-API way on a page that has no Clipboard API — http gets its link", async () => { const { artifact } = await captureArtifact(async () => { await bootConnected(); expect(navigator.clipboard).toBeUndefined(); // The route that was never gated on a secure context: select the text, copy the // selection. Without it an http install has no copy at all, which is a worse // outcome than the deprecated API that solves it. const commands: string[] = []; const boxes: HTMLTextAreaElement[] = []; document.execCommand = ((command: string) => { commands.push(command); // What the browser was told to copy is whatever is selected at this instant, so // this is the moment to look at the throwaway box it is looking at. boxes.push(document.querySelector<HTMLTextAreaElement>("textarea")!); return true; }) as typeof document.execCommand; try { await walkTo((el) => el.classList.contains("lib-row--track")); fireEvent.keyDown(window, { key: "s" }); await waitFor(() => expect(shareLine()?.textContent).toContain("shared")); expect(commands).toEqual(["copy"]); // the link, and nothing else — the box holds the URL and the URL alone, so the // prose around the toolbar line cannot get between the user and the paste expect(boxes[0]!.value).toBe("https://nav.example.com/share/tk1"); expect(boxes[0]!.readOnly).toBe(true); // a focused textarea would raise a phone keyboard // A copy that worked says nothing: no reason, no complaint, just the link. expect(shareLine()!.textContent).not.toContain("no clipboard API"); // and the box is not left behind in the document for the next selector to find expect(document.querySelector("textarea")).toBeNull(); } finally { delete (document as unknown as { execCommand?: unknown }).execCommand; delete (navigator as unknown as { clipboard?: unknown }).clipboard; } }); expectNoDiagnostics(artifact);});
it("Shift+n and Shift+p take a whole record at a time, from wherever the reader is", async () => { // The three tracks of a record are one thing to a listener: `Enter` on its header // plays it from the top and `Alt+r` queues it whole, so leaving it wants one key // and not three presses of `n`. The queue here is 18 tracks in runs of three // (al-0-0, al-0-1, al-1-0 …), which is what makes the asserts below about records // rather than about indexes. const { artifact } = await captureArtifact(async () => { await bootConnected(); fireEvent.click(trackRows()[0]!); await waitFor(() => expect(player().peekState()).toBe("playing")); expect(player().peekCurrent()?.albumId).toBe("al-0-0");
fireEvent.keyDown(window, { key: "N", shiftKey: true }); await waitFor(() => expect(player().peekCursor()).toBe(3)); // the front of the next record, not its second track: a record is heard from // the front, and landing anywhere else would start the listener half-way in expect(player().peekCurrent()?.albumId).toBe("al-0-1"); // cursor 3 is the fourth track of a queue whose runs are three long, which is // the front of the second record — the assert above says which album, this one // says where inside it the listener is dropped. expect(player().peekCursor() % 3).toBe(0);
// Back the same way — to the front of the previous record, not its last track. fireEvent.keyDown(window, { key: "P", shiftKey: true }); await waitFor(() => expect(player().peekCursor()).toBe(0)); expect(player().peekCurrent()?.albumId).toBe("al-0-0");
// There is nothing before this one. `p` at the top of the queue restarts it // rather than wrapping, and wrapping is a mode — the mode for that being repeat // — so an errant Shift+P is a rewind and the queue is not walked off. fireEvent.keyDown(window, { key: "P", shiftKey: true }); await waitFor(() => expect(player().peekState()).toBe("playing")); expect(player().peekCursor()).toBe(0);
// And after the last record there is simply nothing left to play: the queue runs // out the way `n` runs it out, in one keypress rather than a walk off the end. // Five records away is the last one, and every press crosses exactly one. for (const album of ["al-0-1", "al-1-0", "al-1-1", "al-2-0", "al-2-1"]) { fireEvent.keyDown(window, { key: "N", shiftKey: true }); await waitFor(() => expect(player().peekCurrent()?.albumId).toBe(album)); } expect(player().peekCursor()).toBe(15); fireEvent.keyDown(window, { key: "N", shiftKey: true }); await waitFor(() => expect(player().peekState()).toBe("idle"));
// The unshifted pair still moves by one track, which is the difference the two // new keys have to leave alone. fireEvent.click(trackRows()[1]!); await waitFor(() => expect(player().peekCursor()).toBe(1)); fireEvent.keyDown(window, { key: "n" }); await waitFor(() => expect(player().peekCursor()).toBe(2)); fireEvent.keyDown(window, { key: "p" }); await waitFor(() => expect(player().peekCursor()).toBe(1)); }); expectNoDiagnostics(artifact);});