feat(player): a video's related videos, on demand beside it

The player shows what YouTube lists beside the video, without what the
user has watched or hidden. Wide, a Related tab beside the description;
stacked, a button beside the info opens them in a drawer. A row plays in
the same player (Back returns) and the list stays the opened video's.
A switch picks on-topic or Hungarian-trending lists, kept on the account.

Each related row says whether the user follows its channel; the row is
the video card's narrow form with its whole menu. VideoMenu moves to
features/video, where the player can reach it.
This commit is contained in:
2026-10-24 16:57:52 +02:00
parent 8b37c470ba
commit 686c673fb2
18 changed files with 697 additions and 19 deletions
@@ -0,0 +1,175 @@
// @vitest-environment jsdom
//
// A video's related videos, as the player shows them. What is held: a row says when the user follows
// its channel; the region the user picks is asked for and kept on the account; a video marked seen
// here leaves the list (and comes back when the server refuses the mark); reading further sends the
// cursor; and a failure says so rather than drawing an empty list.
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { FloatingTree } from "@floating-ui/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
vi.mock("react-i18next", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-i18next")>();
return {
...actual,
useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" } }),
};
});
vi.mock("../navigation/navigationContext", () => ({
useNavigationActions: () => ({ openChannel: vi.fn() }),
}));
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";
beforeAll(() => {
class Stub {
observe() {}
unobserve() {}
disconnect() {}
takeRecords() {
return [];
}
}
globalThis.ResizeObserver ??= Stub as unknown as typeof ResizeObserver;
globalThis.IntersectionObserver ??= Stub as unknown as typeof IntersectionObserver;
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
clearAll();
});
const row = (id: string, extra: Partial<RelatedVideo> = {}): RelatedVideo =>
({
id,
title: `Video ${id}`,
channel_id: `UC${id}`,
channel_title: `Channel ${id}`,
watch_url: `https://www.youtube.com/watch?v=${id}`,
status: "new",
saved: false,
position_seconds: 0,
followed: false,
...extra,
}) as RelatedVideo;
const page = (items: RelatedVideo[], next: string | null = null) => ({
items,
has_more: next != null,
next_cursor: next,
});
function setup(onPlay: (v: Video, startAt: number) => void = () => {}) {
vi.spyOn(api, "comfortPins").mockResolvedValue({ items: [] } as never);
vi.spyOn(api, "downloadIndex").mockResolvedValue({});
const saved = vi.spyOn(api, "savePrefs").mockResolvedValue({} as never);
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
<QueryClientProvider client={qc}>
<FloatingTree>
<RelatedVideos videoId="SRC" onPlay={onPlay} />
</FloatingTree>
</QueryClientProvider>,
);
return { saved };
}
// A row's title (its picture is a link of the same name).
const title = async (name: string) =>
(await screen.findAllByRole("link", { name })).find((a) => a.hasAttribute("data-nav-open"))!;
const titles = () =>
screen
.queryAllByRole("link")
.filter((a) => a.hasAttribute("data-nav-open"))
.map((a) => a.textContent);
// The menu's surface is visibility:hidden in jsdom: an item is matched on its text.
const menuItem = (label: string) =>
screen.queryAllByRole("menuitem", { hidden: true }).find((b) => b.textContent === label)!;
describe("RelatedVideos", () => {
it("marks the rows whose channel the user follows, and only those", async () => {
vi.spyOn(api, "related").mockResolvedValue(
page([row("A", { followed: true }), row("B"), row("C", { followed: true })]),
);
setup();
await title("Video A");
const marks = screen.getAllByRole("img", { name: "player.related.followed" });
const owners = marks.map((m) => m.closest("[data-video-id]")?.getAttribute("data-video-id"));
expect(owners).toEqual(["A", "C"]);
});
it("asks for the region picked, and keeps the pick on the account", async () => {
const asked = vi.spyOn(api, "related").mockResolvedValue(page([row("A")]));
const { saved } = setup();
await title("Video A");
expect(asked.mock.calls).toEqual([["SRC", "topical", null]]);
fireEvent.click(screen.getByRole("button", { name: "player.related.hu" }));
await waitFor(() => expect(asked.mock.calls).toContainEqual(["SRC", "hu", null]));
expect(saved).toHaveBeenCalledWith({ relatedRegion: "hu" });
});
it("plays a row from where the user left it", async () => {
vi.spyOn(api, "related").mockResolvedValue(page([row("A", { position_seconds: 95 })]));
const onPlay = vi.fn();
setup(onPlay);
fireEvent.click(await title("Video A"));
expect(onPlay).toHaveBeenCalledWith(expect.objectContaining({ id: "A" }), 95);
});
it("drops a video hidden here at once, and brings it back when the server refuses", async () => {
vi.spyOn(api, "related").mockResolvedValue(page([row("A"), row("B")]));
let refuse: (e: Error) => void = () => {};
const write = vi
.spyOn(api, "setState")
.mockReturnValue(new Promise((_, reject) => (refuse = reject)) as never);
setup();
fireEvent.contextMenu((await title("Video A")).closest("[data-video-id]")!);
fireEvent.click(menuItem("card.hide"));
await waitFor(() => expect(write).toHaveBeenCalledWith("A", "hidden"));
expect(titles()).toEqual(["Video B"]);
await act(async () => refuse(new Error("offline")));
expect(titles()).toEqual(["Video A", "Video B"]);
});
it("keeps a video marked watched out of the list once the server has it", async () => {
vi.spyOn(api, "related").mockResolvedValue(page([row("A"), row("B")]));
vi.spyOn(api, "setState").mockResolvedValue(undefined as never);
setup();
fireEvent.contextMenu((await title("Video B")).closest("[data-video-id]")!);
fireEvent.click(menuItem("card.markWatched"));
await waitFor(() => expect(titles()).toEqual(["Video A"]));
});
it("reads further with the cursor the last page gave", async () => {
const asked = vi
.spyOn(api, "related")
.mockResolvedValueOnce(page([row("A")], "CUR1"))
.mockResolvedValueOnce(page([row("B")]));
setup();
await title("Video A");
fireEvent.click(screen.getByRole("button", { name: "player.related.more" }));
await title("Video B");
expect(asked.mock.calls[1]).toEqual(["SRC", "topical", "CUR1"]);
expect(screen.queryByRole("button", { name: "player.related.more" })).toBeNull();
});
it("says so when YouTube refuses, rather than drawing an empty list", async () => {
vi.spyOn(api, "related").mockRejectedValue(
new HttpError(422, "YouTube isn't reachable", undefined),
);
setup();
expect((await screen.findByRole("alert")).textContent).toContain("YouTube isn't reachable");
expect(screen.queryByText("player.related.empty")).toBeNull();
});
it("says when nothing is left that the user has not seen", async () => {
vi.spyOn(api, "related").mockResolvedValue(page([]));
setup();
expect(await screen.findByText("player.related.empty")).toBeTruthy();
expect(screen.queryByRole("alert")).toBeNull();
});
});