diff --git a/frontend/src/components/AppCommandPalette.dom.test.tsx b/frontend/src/components/AppCommandPalette.dom.test.tsx new file mode 100644 index 00000000..9b6e7fde --- /dev/null +++ b/frontend/src/components/AppCommandPalette.dom.test.tsx @@ -0,0 +1,143 @@ +// @vitest-environment jsdom +// +// The palette's DOMAIN half: which rows exist and what they do. The list/filter/keyboard shell +// (`ui/CommandPalette`) has its own tests, so it is stubbed here to hand back the groups it was given — +// what this file pins is the content: modules gated by the account, hidden channels left out, and the +// two `run`s whose ORDER matters. +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { render, cleanup, waitFor } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; + +import type { CommandGroup } from "./ui/CommandPalette"; + +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }), +})); + +let groups: CommandGroup[] = []; +vi.mock("./ui/CommandPalette", () => ({ + default: (props: { groups: CommandGroup[] }) => { + groups = props.groups; + return null; + }, +})); + +const channels = vi.fn(); +const playlists = vi.fn(); +vi.mock("../lib/api", () => ({ + api: { + channels: (...a: unknown[]) => channels(...a), + playlists: (...a: unknown[]) => playlists(...a), + }, +})); + +let me: Record | undefined; +vi.mock("../lib/useMe", () => ({ useMe: () => me })); +vi.mock("../lib/keymap", () => ({ + usePaletteOpen: () => true, + closePalette: vi.fn(), + toggleKeyboardHelp: vi.fn(), +})); + +const calls: string[] = []; +const setPage = vi.fn((page: string, then?: () => void) => { + calls.push(`setPage:${page}`); + then?.(); +}); +vi.mock("./navigationContext", () => ({ + useNavigationActions: () => ({ setPage, openChannel: vi.fn() }), +})); +vi.mock("./playlistsContext", () => ({ + usePlaylistsActions: () => ({ + setSelectedId: (id: number) => calls.push(`select:${id}`), + }), +})); +vi.mock("./prefsContext", () => ({ + usePrefs: () => ({ theme: { scheme: "default" }, setTheme: vi.fn() }), +})); +vi.mock("./savedViewsContext", () => ({ + useSavedViews: () => ({ views: [], apply: vi.fn() }), +})); +const requestSurprise = vi.fn(); +vi.mock("../lib/homeIntent", () => ({ requestSurprise: () => requestSurprise() })); + +import AppCommandPalette from "./AppCommandPalette"; + +const user = (over: Record = {}) => ({ + id: 1, + role: "user", + is_demo: false, + plex_enabled: false, + ...over, +}); + +function mount() { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + render( + + + , + ); +} + +const group = (id: string) => groups.find((g) => g.id === id); +const ids = (id: string) => group(id)?.items.map((i) => i.id) ?? []; + +beforeEach(() => { + groups = []; + calls.length = 0; + me = user(); + setPage.mockClear(); + requestSurprise.mockClear(); + channels.mockReset().mockResolvedValue([]); + playlists.mockReset().mockResolvedValue([]); +}); +afterEach(cleanup); + +describe("AppCommandPalette", () => { + it("offers only the modules this account can open, in nav order, and Settings", () => { + mount(); + expect(ids("modules")).toContain("page:feed"); + expect(ids("modules")).not.toContain("page:plex"); + expect(ids("modules")).not.toContain("page:config"); // admin-only + expect(ids("modules").slice(-1)).toEqual(["page:settings"]); + + cleanup(); + me = user({ role: "admin", plex_enabled: true }); + mount(); + expect(ids("modules")).toContain("page:plex"); + expect(ids("modules")).toContain("page:config"); + }); + + it("leaves out the channels the user has hidden", async () => { + channels.mockResolvedValue([ + { id: "UC1", title: "Shown", handle: "@shown", hidden: false }, + { id: "UC2", title: "Hidden", handle: "@hidden", hidden: true }, + ]); + mount(); + await waitFor(() => expect(group("channels")).toBeTruthy()); + expect(ids("channels")).toEqual(["channel:UC1"]); + }); + + it("selects the playlist BEFORE switching to the page, so it opens on that list", async () => { + playlists.mockResolvedValue([{ id: 7, name: "Later", item_count: 3 }]); + mount(); + await waitFor(() => expect(group("playlists")).toBeTruthy()); + group("playlists")!.items[0]!.run(); + expect(calls).toEqual(["select:7", "setPage:playlists"]); + }); + + it("asks for the surprise once the navigation to Home has happened, not before", () => { + mount(); + const surprise = group("actions")!.items.find((i) => i.id === "action:surprise")!; + // Over an open player the push lands a moment after the call, and the token must name the + // entry that push makes (lib/homeIntent) — so it rides `setPage`'s `then`, not the next line. + setPage.mockImplementationOnce((page: string) => void calls.push(`setPage:${page}`)); + surprise.run(); + expect(requestSurprise).not.toHaveBeenCalled(); + const then = setPage.mock.lastCall?.[1]; + expect(setPage.mock.lastCall?.[0]).toBe("home"); + then?.(); + expect(requestSurprise).toHaveBeenCalledTimes(1); + }); +}); diff --git a/frontend/src/components/Playlists.dom.test.tsx b/frontend/src/components/Playlists.dom.test.tsx index 522b5a83..43ae66a3 100644 --- a/frontend/src/components/Playlists.dom.test.tsx +++ b/frontend/src/components/Playlists.dom.test.tsx @@ -55,6 +55,7 @@ vi.mock("./PlayerModal", async () => { }); import Playlists from "./Playlists"; +import { PageToolbarSlot } from "./ui/pageToolbarSlot"; import { api, HttpError, type Video } from "../lib/api"; import { qk } from "../lib/queryKeys"; import { patchCachedProgress } from "../lib/progressCache"; @@ -106,9 +107,15 @@ function mount(lists: Record, prefs: Record = ); qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); qc.setQueryData(qk.me(), { id: 1, can_write: true, prefs: {}, preferences: prefs }); + // The header portals into the shell's fixed toolbar band; without a slot it renders nothing, and + // it went untested for exactly that reason. + const slot = document.createElement("div"); + document.body.appendChild(slot); const tree = () => ( - + + + ); const view = render(tree()); @@ -128,6 +135,7 @@ beforeEach(() => { afterEach(() => { cleanup(); vi.restoreAllMocks(); + document.body.replaceChildren(); }); describe("Playlists — the row the player is launched with", () => { @@ -403,3 +411,41 @@ describe("Playlists — the rows are a keyboard list", () => { await waitFor(() => expect(h.player?.video.id).toBe("B")); }); }); + +// The header's meta line and its view-controls gate were typechecked and linted but never rendered, +// so a regression in either shipped green (E9 review). The count and the runtime sum the WHOLE +// list; an unknown duration counts as nothing rather than poisoning the sum; and a list of one has +// no view to change. +describe("Playlists · the header", () => { + // MISSING, not null: `3000 + null` is 3000 in JS, so only an absent field shows whether the sum + // guards an unknown duration or would turn the whole runtime into NaN. + const untimed = (id: string) => { + const { duration_seconds: _drop, ...rest } = vid(id, 0); + return rest as unknown as Video; + }; + const meta = async () => + ( + await screen.findByText( + (_, el) => el?.tagName === "SPAN" && /^playlists\.itemCount/.test(el.textContent ?? ""), + ) + ).textContent; + + it("sums what is known, and says nothing about a runtime nothing sums to", async () => { + mount({ 1: [vid("A", 0), untimed("B")] }); + expect(await meta()).toBe("playlists.itemCount · 50m"); + cleanup(); + + mount({ 1: [untimed("C")] }); + expect(await meta()).toBe("playlists.itemCount"); + }); + + it("offers the view controls only once there is more than one row to arrange", async () => { + mount({ 1: [vid("A", 0)] }); + await screen.findByText("Video A"); + expect(screen.queryByText("playlists.groupByChannel")).toBeNull(); + cleanup(); + + mount({ 1: [vid("A", 0), vid("B", 0)] }); + expect(await screen.findByText("playlists.groupByChannel")).toBeTruthy(); + }); +}); diff --git a/frontend/src/components/PlexPlaylistView.header.dom.test.tsx b/frontend/src/components/PlexPlaylistView.header.dom.test.tsx new file mode 100644 index 00000000..6bceb0b8 --- /dev/null +++ b/frontend/src/components/PlexPlaylistView.header.dom.test.tsx @@ -0,0 +1,73 @@ +// @vitest-environment jsdom +// +// The Plex playlist header's meta line — the count and the playlist's total runtime, mirroring the +// YouTube playlist header — was never rendered by a test, so a regression in the sum shipped green +// (E9 review). The runtime sums the WHOLE list, an unknown duration counts as nothing, and a list +// nothing sums for says no runtime at all. +import { describe, it, expect, vi, beforeAll, afterEach } from "vitest"; +import { render, cleanup, screen } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; + +vi.mock("react-i18next", async (importOriginal) => ({ + ...(await importOriginal()), + useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" } }), +})); + +import PlexPlaylistView from "./PlexPlaylistView"; +import { api, type PlexCard } from "../lib/api"; + +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(); +}); + +// An unknown runtime is an ABSENT field: `5400 + null` is 5400 in JS, so null would prove nothing +// about the sum's guard; `undefined` turns an unguarded sum into NaN. +const movie = (id: string, duration_seconds?: number) => + ({ + id, + type: "movie", + title: `Movie ${id}`, + year: 2020, + thumb: "", + duration_seconds, + }) as unknown as PlexCard; + +async function meta(items: PlexCard[]) { + vi.spyOn(api, "plexPlaylist").mockResolvedValue({ id: 5, title: "Films", items } as never); + render( + + {}} onPlay={() => {}} /> + , + ); + await screen.findByText(`Movie ${items[0]!.id}`); + return screen.getByText( + (_, el) => /^plex\.browse\.items/.test(el?.textContent ?? "") && el?.childElementCount === 0, + ).textContent; +} + +describe("PlexPlaylistView · the header's meta line", () => { + it("sums the known runtimes and counts an unknown one as nothing", async () => { + expect(await meta([movie("1", 5400), movie("2"), movie("3", 1800)])).toBe( + "plex.browse.items · 2h 0m", + ); + }); + + it("drops the runtime when nothing sums", async () => { + expect(await meta([movie("1")])).toBe("plex.browse.items"); + }); +}); diff --git a/frontend/src/components/ShareDialog.dom.test.tsx b/frontend/src/components/ShareDialog.dom.test.tsx new file mode 100644 index 00000000..15f3a05b --- /dev/null +++ b/frontend/src/components/ShareDialog.dom.test.tsx @@ -0,0 +1,73 @@ +// @vitest-environment jsdom +// +// The share dialog's link row says two things with colour alone: a PROTECTED link's lock is lit, and +// Revoke is the destructive one. Both colours once sat on the button, where the ghost variant's own +// colour class outranks them (clsx does not merge Tailwind), so a password-protected link looked +// unprotected and Revoke hovered neutral. They live on the ICON now; this pins them there. +import { describe, it, expect, afterEach, vi } from "vitest"; +import { render, screen, cleanup } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import type { ReactNode } from "react"; + +// Partial: the import graph reaches `src/i18n`, which initialises against the real +// `initReactI18next`, so a wholesale mock throws before any test runs. +vi.mock("react-i18next", async (importOriginal) => ({ + ...(await importOriginal()), + useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }), +})); +vi.mock("./ui/Modal", () => ({ default: ({ children }: { children: ReactNode }) => children })); +vi.mock("./confirmContext", () => ({ useConfirm: () => async () => false })); +vi.mock("../lib/api", () => ({ + api: { + shareRecipients: async () => [], + downloadLinks: async () => [ + { + id: 1, + token: "a", + url: "/watch/a", + allow_download: false, + has_password: true, + expires_at: null, + view_count: 0, + created_at: null, + }, + { + id: 2, + token: "b", + url: "/watch/b", + allow_download: false, + has_password: false, + expires_at: null, + view_count: 0, + created_at: null, + }, + ], + }, +})); + +import ShareDialog from "./ShareDialog"; +import type { DownloadJob } from "../lib/api"; + +afterEach(cleanup); + +const iconClass = (button: HTMLElement) => button.querySelector("svg")?.getAttribute("class") ?? ""; + +describe("ShareDialog · a link row's state colours", () => { + it("lights the lock of a protected link only, and paints Revoke as danger — on the icon", async () => { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + render( + + {}} /> + , + ); + const protectedLock = await screen.findByRole("button", { + name: "downloads.share.changePassword", + }); + const openLock = screen.getByRole("button", { name: "downloads.share.setPassword" }); + expect(iconClass(protectedLock)).toContain("text-accent"); + expect(iconClass(openLock)).not.toContain("text-accent"); + + for (const revoke of screen.getAllByRole("button", { name: "downloads.share.revoke" })) + expect(iconClass(revoke)).toContain("text-danger"); + }); +}); diff --git a/frontend/src/components/ui/Banner.dom.test.tsx b/frontend/src/components/ui/Banner.dom.test.tsx new file mode 100644 index 00000000..798abc51 --- /dev/null +++ b/frontend/src/components/ui/Banner.dom.test.tsx @@ -0,0 +1,31 @@ +// @vitest-environment jsdom +import { describe, it, expect, afterEach, vi } from "vitest"; +import { render, screen, cleanup } from "@testing-library/react"; +import { Info } from "lucide-react"; + +vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (k: string) => k }) })); + +import Banner from "./Banner"; + +afterEach(cleanup); + +// The dismiss button is an icon, so its name is all a screen reader gets. A caller that forgets +// `dismissTitle` must still ship a NAMED control — the generic "Close" — never an unnamed one. +describe("Banner · the dismiss button's name", () => { + it("falls back to the generic Close, and takes the caller's name when given", () => { + render( + {}}> + News + , + ); + expect(screen.getByRole("button", { name: "common.close" })).toBeTruthy(); + cleanup(); + + render( + {}} dismissTitle="Hide the notes"> + News + , + ); + expect(screen.getByRole("button", { name: "Hide the notes" })).toBeTruthy(); + }); +}); diff --git a/frontend/src/lib/keymap.test.ts b/frontend/src/lib/keymap.test.ts index 7377bf68..d2a6f2e0 100644 --- a/frontend/src/lib/keymap.test.ts +++ b/frontend/src/lib/keymap.test.ts @@ -33,6 +33,13 @@ describe("matches", () => { expect(matches(press({ key: "ArrowLeft", shiftKey: true }), "ArrowLeft")).toBe(false); }); + // AltGr is a constant-use key on this user's HU layout (@, [, ], {, }, \ all sit behind it), and on + // Windows it arrives as Ctrl+Alt. Typing one of those must never fire a bare-key row or a Mod row. + it("rejects an Alt- or AltGr-modified key, even when its Ctrl half would match Mod", () => { + expect(matches(press({ key: "a", altKey: true }), "a")).toBe(false); + expect(matches(press({ key: "k", ctrlKey: true, altKey: true }), "Mod+k")).toBe(false); + }); + it("treats Mod as Ctrl or Cmd", () => { expect(matches(press({ key: "k", ctrlKey: true }), "Mod+k")).toBe(true); expect(matches(press({ key: "k", metaKey: true }), "Mod+k")).toBe(true);