fix(player): a related video played is tracked, and its list is honest about its state

A related video played in place is the player's item now: its title and its own watched /
playlist / download controls, its progress checkpointed and resumed, marked watched at its end —
and its end does not step the queue. Back returns to the opened video, where it was left.

The related list:
- its marks announce through the shared notice (the Notification Center finds them), join the
  host's player session (the feed refetches on close), and stay per write, so an earlier answer no
  longer undoes a later mark still on its way;
- every host's state write patches the cached related lists, which are never refetched;
- kept for the session (gcTime), a retry asks for the page that failed, a list read so far with
  nothing unseen says so, a refusal a retry cannot answer offers none, and the followed mark names
  itself on hover.

Turned off on the instance (a limit of 0), the tab, the drawer button and the live-search buttons
are left out.

Keys: the player's keys and its focus reclaim defer to a layer above it (the drawer); going wide
moves the drawer's list into the panel's tab; `j` goes on from the slot of a row removed inside the
top layer; the help sheet lists the list keys over a layer that holds a list.
This commit is contained in:
2026-10-25 00:32:28 +02:00
parent d53729a63d
commit b5045165c0
30 changed files with 1024 additions and 207 deletions
@@ -23,7 +23,8 @@ vi.mock("../video/AddToPlaylist", () => ({ default: () => null }));
import { RelatedVideos } from "./RelatedVideos";
import { api, HttpError, type RelatedVideo, type Video } from "../../lib/api";
import { clearAll } from "../../lib/notifications";
import { clearAll, getNotifications } from "../../lib/notifications";
import { qk } from "../../lib/queryKeys";
beforeAll(() => {
class Stub {
@@ -63,7 +64,10 @@ const page = (items: RelatedVideo[], next: string | null = null) => ({
next_cursor: next,
});
function setup(onPlay: (v: Video, startAt: number) => void = () => {}) {
function setup(
onPlay: (v: Video, startAt: number) => void = () => {},
onWrite?: (write: Promise<unknown>) => void,
) {
vi.spyOn(api, "comfortPins").mockResolvedValue({ items: [] } as never);
vi.spyOn(api, "downloadIndex").mockResolvedValue({});
const saved = vi.spyOn(api, "savePrefs").mockResolvedValue({} as never);
@@ -71,11 +75,11 @@ function setup(onPlay: (v: Video, startAt: number) => void = () => {}) {
render(
<QueryClientProvider client={qc}>
<FloatingTree>
<RelatedVideos videoId="SRC" onPlay={onPlay} />
<RelatedVideos videoId="SRC" onPlay={onPlay} onWrite={onWrite} />
</FloatingTree>
</QueryClientProvider>,
);
return { saved };
return { saved, qc };
}
// A row's title (its picture is a link of the same name).
@@ -166,6 +170,144 @@ describe("RelatedVideos", () => {
expect(screen.queryByText("player.related.empty")).toBeNull();
});
// A deferred answer, settled when the test says.
const deferred = () => {
let resolve: () => void = () => {};
let reject: (e: Error) => void = () => {};
const promise = new Promise<never>((res, rej) => {
resolve = res as () => void;
reject = rej;
});
return { promise, resolve, reject };
};
it("keeps a row hidden while its hide is on its way, though an earlier save landed", async () => {
vi.spyOn(api, "related").mockResolvedValue(page([row("A"), row("B")]));
const save = deferred();
const saving = vi.spyOn(api, "watchLaterAdd").mockReturnValue(save.promise as never);
const hide = deferred();
const hiding = vi.spyOn(api, "setState").mockReturnValue(hide.promise as never);
setup();
const card = (await title("Video A")).closest("[data-video-id]")!;
fireEvent.contextMenu(card);
fireEvent.click(menuItem("card.saveForLater"));
await waitFor(() => expect(saving).toHaveBeenCalledWith("A"));
fireEvent.contextMenu(card);
fireEvent.click(menuItem("card.hide"));
await waitFor(() => expect(hiding).toHaveBeenCalledWith("A", "hidden"));
expect(titles()).toEqual(["Video B"]);
await act(async () => save.resolve());
expect(titles()).toEqual(["Video B"]);
});
it("announces a hide with the video it names, for the notification center to find", async () => {
vi.spyOn(api, "related").mockResolvedValue(page([row("A")]));
vi.spyOn(api, "setState").mockResolvedValue(undefined as never);
const writes: Promise<unknown>[] = [];
setup(undefined, (w) => void writes.push(w));
fireEvent.contextMenu((await title("Video A")).closest("[data-video-id]")!);
fireEvent.click(menuItem("card.hide"));
await waitFor(() => expect(getNotifications().length).toBeGreaterThan(0));
expect(getNotifications().map((n) => n.meta)).toContainEqual({
kind: "video-hidden",
videoId: "A",
title: "Video A",
channelId: "UCA",
channelName: "Channel A",
});
// And the write reached the host's session.
expect(writes).toHaveLength(1);
});
it("flips a row's bookmark at once, and back when the server refuses", async () => {
vi.spyOn(api, "related").mockResolvedValue(page([row("A")]));
const save = deferred();
vi.spyOn(api, "watchLaterAdd").mockReturnValue(save.promise as never);
setup();
const card = (await title("Video A")).closest("[data-video-id]")!;
// What the menu offers is the row's state: un-save once saved.
const offers = (label: string) => {
fireEvent.contextMenu(card);
return !!menuItem(label);
};
expect(offers("card.saveForLater")).toBe(true);
fireEvent.click(menuItem("card.saveForLater"));
await waitFor(() => expect(offers("card.menu.unsave")).toBe(true));
fireEvent.keyDown(document.activeElement ?? document.body, { key: "Escape" });
await act(async () => save.reject(new Error("offline")));
await waitFor(() => expect(offers("card.saveForLater")).toBe(true));
});
it("is kept for the session, not collected when the list closes", async () => {
vi.spyOn(api, "related").mockResolvedValue(page([row("A")]));
const { qc } = setup();
await title("Video A");
const [cached] = qc.getQueryCache().findAll({ queryKey: qk.related() });
expect(cached!.options.gcTime).toBe(Infinity);
});
it("says the next page failed under the rows it has, and retries that page", async () => {
const asked = vi
.spyOn(api, "related")
.mockResolvedValueOnce(page([row("A")], "CUR1"))
.mockRejectedValueOnce(new HttpError(422, "YouTube isn't reachable", undefined))
.mockResolvedValueOnce(page([row("B")]));
setup();
await title("Video A");
fireEvent.click(screen.getByRole("button", { name: "player.related.more" }));
expect((await screen.findByRole("alert")).textContent).toContain("YouTube isn't reachable");
expect(titles()).toEqual(["Video A"]);
fireEvent.click(screen.getByRole("button", { name: "common.retry" }));
await title("Video B");
expect(asked.mock.calls.map((c) => c[2])).toEqual([null, "CUR1", "CUR1"]);
});
it("with nothing unseen read so far, says so above Show more, and retries the page it failed", async () => {
const asked = vi
.spyOn(api, "related")
.mockResolvedValueOnce(page([], "CUR1"))
.mockRejectedValueOnce(new HttpError(422, "YouTube isn't reachable", undefined))
.mockResolvedValueOnce(page([row("B")]));
setup();
expect(await screen.findByText("player.related.emptySoFar")).toBeTruthy();
expect(screen.queryByText("player.related.empty")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "player.related.more" }));
await screen.findByRole("alert");
fireEvent.click(screen.getByRole("button", { name: "common.retry" }));
await title("Video B");
expect(asked.mock.calls.map((c) => c[2])).toEqual([null, "CUR1", "CUR1"]);
});
it.each([
["the day's cap", { code: "refused", reason: "related_daily_limit", limit: 5 }],
["turned off", { code: "refused", reason: "related_disabled" }],
["the shared budget", { code: "youtube", reason: "quota" }],
])("offers no retry a retry cannot answer: %s", async (_name, detail) => {
vi.spyOn(api, "related").mockRejectedValue(new HttpError(429, "Refused", detail));
setup();
expect((await screen.findByRole("alert")).textContent).toContain("Refused");
expect(screen.queryByRole("button", { name: "common.retry" })).toBeNull();
});
it("offers a retry where trying again can help", async () => {
vi.spyOn(api, "related").mockRejectedValue(
new HttpError(422, "YouTube isn't reachable", { code: "youtube", reason: "unavailable" }),
);
setup();
await screen.findByRole("alert");
expect(screen.getByRole("button", { name: "common.retry" })).toBeTruthy();
});
it("names the followed mark on hover", async () => {
vi.spyOn(api, "related").mockResolvedValue(page([row("A", { followed: true })]));
setup();
await title("Video A");
const mark = screen.getByRole("img", { name: "player.related.followed" });
fireEvent.mouseEnter(mark.parentElement!);
fireEvent.pointerEnter(mark.parentElement!, { pointerType: "mouse" });
expect(await screen.findByText("player.related.followed")).toBeTruthy();
});
it("says when nothing is left that the user has not seen", async () => {
vi.spyOn(api, "related").mockResolvedValue(page([]));
setup();