Files
siftlode/frontend/src/components/Feed.ytsort.dom.test.tsx
T
peter c3d88d9b20 refactor: component files export only components; lint fails on a warning
The 43 react-refresh/only-export-components warnings the gate let through meant an edit to a
provider (or AnchoredPopover, Toaster, plexDetailUi, …) could not be hot-swapped: Fast Refresh
reloads a module that also exports hooks or helpers.

- Each provider's contexts, the types its hooks return and the hooks themselves live in a sibling
  context module (navigationContext.ts, channelsContext.ts, …); the provider file keeps the
  component. loadAccountFilters moved next to the feed filters' defaults (feedFiltersInit.ts),
  following navigationInit/playlistsInit.
- Helpers that sat in component files have their own modules: welcomeMode, downloadTitle,
  plexPlayable, channelSync, ui/anchoredPopoverHooks, ui/pageToolbarSlot, ui/pagerContent,
  ui/toastLevels, ui/overlayOrder, ui/tableAlign, lib/plexDetail; the cells of the channel columns
  and the registry's page wrappers are components files of their own (channelCells, modulePages).
- usePersistedTab, an alias of useAccountPersistedState, is gone; its callers use the original.

npm run lint is now eslint --max-warnings 0, so a warning fails the gate like an error does.
2026-09-17 02:59:09 +02:00

119 lines
4.1 KiB
TypeScript

// @vitest-environment jsdom
//
// The live-YouTube results' Sort control, wired end to end: the pref it writes, the key and
// direction Feed hands to sortYtResults, and the order that reaches the grid. sortYtResults itself
// is pinned in feedSort.yt.test.ts; a deep-review of the 2026-09 bug hunt found that the CALL SITE
// could ignore the chosen direction (or skip the sort entirely) with every lane green.
//
// The virtualised grid lays out nothing in jsdom, so it is replaced by a plain list that shows the
// order Feed gave it — which is exactly the thing under test.
import { describe, it, expect, vi, beforeAll, afterEach } from "vitest";
import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
vi.mock("react-i18next", async (importOriginal) => ({
...(await importOriginal<typeof import("react-i18next")>()),
useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" } }),
}));
vi.mock("./wizardContext", () => ({ useWizard: () => ({ openWizard: vi.fn() }) }));
vi.mock("./VirtualFeed", () => ({
default: ({ items }: { items: { id: string; title: string }[] }) => (
<ol aria-label="results">
{items.map((v) => (
<li key={v.id}>{v.title}</li>
))}
</ol>
),
}));
import Feed from "./Feed";
import { api, DEFAULT_TAG_MODES, type FeedFilters, type Video } from "../lib/api";
import { qk } from "../lib/queryKeys";
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();
});
const FILTERS: FeedFilters = {
tags: [],
tagModes: DEFAULT_TAG_MODES,
channelIds: [],
q: "",
sort: "newest",
scope: "my",
includeNormal: true,
includeShorts: false,
includeLive: false,
show: "unwatched",
};
const hit = (id: string, duration_seconds: number): Video =>
({
id,
title: `hit ${id}`,
channel_id: "UCx",
channel_title: "Channel",
status: "new",
position_seconds: 0,
duration_seconds,
published_at: "2026-01-01T00:00:00Z",
watch_url: `https://www.youtube.com/watch?v=${id}`,
}) as unknown as Video;
const order = () =>
Array.from(screen.getByRole("list", { name: "results" }).querySelectorAll("li")).map(
(li) => li.textContent,
);
describe("Feed — sorting the live YouTube results", () => {
it("hands the grid the results in the key AND direction the viewer picked", async () => {
vi.spyOn(api, "savePrefs").mockResolvedValue(undefined as never);
vi.spyOn(api, "searchYoutube").mockResolvedValue({
items: [hit("a", 300), hit("b", 100), hit("c", 200)],
next_cursor: null,
source: "scrape",
} as never);
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
qc.setQueryData(qk.me(), { id: 1, can_write: true, prefs: {} });
render(
<QueryClientProvider client={qc}>
<Feed
filters={FILTERS}
setFilters={() => {}}
view="cards"
setView={() => {}}
canRead
ytSearch="lemmino"
onYtSearch={() => {}}
onExitYtSearch={() => {}}
/>
</QueryClientProvider>,
);
// Relevance is the provider's own ranking — the order the results arrived in.
await waitFor(() => expect(order()).toEqual(["hit a", "hit b", "hit c"]));
fireEvent.click(screen.getByRole("button", { name: /^feed\.sortLabel:/ }));
const duration = (await screen.findAllByRole("menuitemradio", { hidden: true })).find((o) =>
o.textContent?.includes("feed.sortKey.duration"),
);
fireEvent.click(duration!);
fireEvent.click(await screen.findByText("feed.dirAsc"));
await waitFor(() => expect(order()).toEqual(["hit b", "hit c", "hit a"]));
fireEvent.click(screen.getByText("feed.dirDesc"));
await waitFor(() => expect(order()).toEqual(["hit a", "hit c", "hit b"]));
});
});