E5 S4: Plex Discover rail-surface (default landing)

A dedicated Plex "Discover" landing — a stack of horizontal Carousel rails
served from ONE consolidated read (serve-from-DB, no live Plex/TMDB call):

- GET /api/plex/discover → continue_watching (in-progress movies + shows, most
  recently progressed) · recently_added · genres (top-N tiles) ·
  because_you_watched (recs of the most-recent watched, TMDB-enriched movie,
  resolved to library rows by guid via serve_block's resolver).
- GET /api/plex/surprise → a fresh random, scope-bounded sample for the ↻ rail.

Frontend: PlexDiscover.tsx (rails reuse the S1 Carousel + S3 PlexPosterCard;
colored genre tiles → tap to filter the grid; ↻ reshuffles the surprise rail
alone). Discover is now the root sub-view; the flat grid becomes the bookmarkable
"Browse all" secondary view (?v=browse) reached by a header search/filter (a
browse-intent flip) or the new Discover⟷Browse toggle.

resolve_recs is promoted from _resolve_recs (now cross-module). Tests:
test_plex_discover.py (rail shape/order, continue-watching, because-you-watched
+ null, surprise bounds, scope) and PlexDiscover.dom.test.tsx; plexSubUrl
round-trip updated for discover-root/grid-browse. Backend lane 393, vitest 332.
This commit is contained in:
2026-08-20 22:15:54 +02:00
parent 5b5e76b73d
commit f9b63745f9
13 changed files with 1022 additions and 9 deletions
+49 -2
View File
@@ -25,6 +25,8 @@ import { useHistorySubview } from "../lib/history";
import { PLEX_SUB_URL, type Sub } from "./plexSubUrl";
import { toggleWatchState } from "../lib/plexWatch";
import SortControl from "./SortControl";
import SegmentedToggle from "./SegmentedToggle";
import PlexDiscover from "./PlexDiscover";
import { PageToolbar } from "./PageShell";
import ActiveFilterChips from "./ActiveFilterChips";
import { StateMessage } from "./QueryState";
@@ -70,7 +72,9 @@ export default function PlexBrowse() {
const sortOptions = plexSortOptions(scope, (k) => t(`plex.sort.${k}`));
// Same idiom for the search scope-pill: a movie-only scope can't hold the Episode field.
const fieldState = healPlexField(field, scope);
const sub = useHistorySubview<Sub>({ kind: "grid" }, PLEX_SUB_URL);
// Discover is the landing (E5 S4); the flat grid is the "Browse all" secondary view. A header search
// or an added filter is a browse intent → flip to the grid (below); an explicit toggle returns.
const sub = useHistorySubview<Sub>({ kind: "discover" }, PLEX_SUB_URL);
// Sidebar asked to open a playlist → push it as a subview (browser Back returns to the grid), then
// clear the signal so it doesn't re-open.
@@ -95,6 +99,19 @@ export default function PlexBrowse() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [jumpTo]);
// Discover → grid on a browse intent: when a header search or a filter FIRST becomes active while on
// the Discover landing, switch to the flat grid (which consumes q/filters). Only on the off→on edge,
// so a pre-existing (persisted) filter doesn't yank a returning user off Discover on mount, and a
// Back to Discover with the search still in the box doesn't immediately re-flip.
const browseIntent = !!dq || plexFilterCount(filters) > 0;
const prevIntent = useRef(browseIntent);
useEffect(() => {
if (sub.view.kind === "discover" && browseIntent && !prevIntent.current) {
sub.open({ kind: "grid" });
}
prevIntent.current = browseIntent;
}, [browseIntent, sub]);
// Opening a show/player replaces the grid entirely (the component returns early below), so the
// scroll container resets to the top. Remember where the grid was scrolled when leaving it, and
// restore it when we come back — so the browser/mouse Back from the player lands on the same card
@@ -124,7 +141,7 @@ export default function PlexBrowse() {
const tag = (el?.tagName || "").toLowerCase();
if (tag === "input" || tag === "textarea" || tag === "select" || el?.isContentEditable)
return;
if (["show", "season", "info", "person", "playlist"].includes(sub.view.kind)) {
if (["grid", "show", "season", "info", "person", "playlist"].includes(sub.view.kind)) {
e.preventDefault();
sub.back();
}
@@ -337,12 +354,42 @@ export default function PlexBrowse() {
);
}
// Discover ⟷ Browse switch, shown on both surfaces so either can return to the other.
const viewToggle = (
<SegmentedToggle
size="md"
ariaLabel={t("plex.view.label")}
options={[
{ value: "discover", label: t("plex.discover.tab") },
{ value: "grid", label: t("plex.view.browse") },
]}
value={sub.view.kind === "discover" ? "discover" : "grid"}
onChange={(v) => sub.open(v === "discover" ? { kind: "discover" } : { kind: "grid" })}
/>
);
if (sub.view.kind === "discover") {
return (
<div className="p-4 max-w-[1600px] mx-auto">
<div className="mb-4 flex items-center">{viewToggle}</div>
<PlexDiscover
scope={scope}
onOpenCard={onCard}
onInfoCard={onInfo}
onGenre={(g) => applyFilter({ genres: [g] })}
onSeeAllRecent={() => sub.open({ kind: "grid" })}
/>
</div>
);
}
return (
<div className="p-4 max-w-[1600px] mx-auto">
{/* The title count is fixed chrome — it portals into the shell's fixed band so it stays put
while only the poster grid scrolls. */}
<PageToolbar>
<div className="px-4 pt-3 pb-1 max-w-[1600px] mx-auto flex items-center gap-2">
{viewToggle}
<p className="text-xs text-muted">
{browseQ.isLoading
? " "
@@ -0,0 +1,181 @@
// @vitest-environment jsdom
//
// E5 S4: the Plex Discover landing. Covers the rail surface served from the mocked /discover +
// /surprise calls — that each non-empty rail renders, the genre tile fires onGenre, the recently-added
// "see all" fires onSeeAllRecent, the ↻ reshuffle refetches the surprise rail alone, and an all-empty
// payload shows the empty message. i18n is key-passthrough; the api is mocked so queries resolve
// synchronously. The rails scroll inside a Carousel (useHScroll → ResizeObserver), stubbed for jsdom.
import { describe, it, expect, afterEach, beforeAll, vi } from "vitest";
import { render, screen, fireEvent, cleanup, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
beforeAll(() => {
class Stub {
observe() {}
unobserve() {}
disconnect() {}
takeRecords() {
return [];
}
}
globalThis.ResizeObserver ??= Stub as unknown as typeof ResizeObserver;
});
vi.mock("react-i18next", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-i18next")>();
// Interpolate {{title}} so the because-you-watched heading is asserted with its anchor name.
return {
...actual,
useTranslation: () => ({
t: (key: string, opts?: Record<string, unknown>) =>
opts?.title ? `${key}:${opts.title}` : key,
}),
};
});
const plexDiscover = vi.fn();
const plexSurprise = vi.fn();
const plexSetState = vi.fn((..._a: unknown[]) => Promise.resolve());
vi.mock("../lib/api", () => ({
api: {
plexDiscover: (...a: unknown[]) => plexDiscover(...a),
plexSurprise: (...a: unknown[]) => plexSurprise(...a),
plexSetState: (...a: unknown[]) => plexSetState(...a),
},
}));
import PlexDiscover from "./PlexDiscover";
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
const card = (id: string, title: string, type: "movie" | "show" = "movie") => ({
id,
type,
title,
year: 2000,
duration_seconds: 3600,
thumb: `/api/plex/image/${id}`,
playable: "direct",
status: "new",
position_seconds: 0,
});
const fullPayload = {
scope: "both",
continue_watching: [card("cw1", "Resume Me")],
recently_added: [card("ra1", "Just Added")],
genres: [{ value: "Drama", count: 12 }],
because_you_watched: { anchor: { id: "a1", title: "Anchor" }, items: [card("bw1", "Rec One")] },
};
function wrap(ui: React.ReactElement) {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);
}
const noop = () => {};
describe("PlexDiscover", () => {
it("renders each non-empty rail, the genre tiles, and the surprise sample", async () => {
plexDiscover.mockResolvedValue(fullPayload);
plexSurprise.mockResolvedValue({ scope: "both", items: [card("sp1", "Random Pick")] });
wrap(
<PlexDiscover
scope="both"
onOpenCard={noop}
onInfoCard={noop}
onGenre={noop}
onSeeAllRecent={noop}
/>,
);
await screen.findByText("plex.discover.continueWatching");
expect(screen.getByText("plex.discover.recentlyAdded")).toBeTruthy();
expect(screen.getByText("plex.discover.surprise")).toBeTruthy();
expect(screen.getByText("plex.discover.byGenre")).toBeTruthy();
// The because-you-watched heading interpolates the anchor title.
expect(screen.getByText("plex.discover.becauseWatched:Anchor")).toBeTruthy();
// A card from each rail is present (title rendered in the poster label).
expect(screen.getAllByText("Resume Me").length).toBeGreaterThan(0);
expect(screen.getAllByText("Just Added").length).toBeGreaterThan(0);
expect(screen.getAllByText("Random Pick").length).toBeGreaterThan(0);
expect(screen.getAllByText("Rec One").length).toBeGreaterThan(0);
expect(plexDiscover).toHaveBeenCalledWith("both", "en");
});
it("fires onGenre with the tile's value", async () => {
plexDiscover.mockResolvedValue(fullPayload);
plexSurprise.mockResolvedValue({ scope: "both", items: [] });
const onGenre = vi.fn();
wrap(
<PlexDiscover
scope="both"
onOpenCard={noop}
onInfoCard={noop}
onGenre={onGenre}
onSeeAllRecent={noop}
/>,
);
fireEvent.click(await screen.findByText("Drama"));
expect(onGenre).toHaveBeenCalledWith("Drama");
});
it("fires onSeeAllRecent from the recently-added rail's see-all", async () => {
plexDiscover.mockResolvedValue(fullPayload);
plexSurprise.mockResolvedValue({ scope: "both", items: [] });
const onSeeAllRecent = vi.fn();
wrap(
<PlexDiscover
scope="both"
onOpenCard={noop}
onInfoCard={noop}
onGenre={noop}
onSeeAllRecent={onSeeAllRecent}
/>,
);
fireEvent.click(await screen.findByRole("button", { name: "common.seeAll" }));
expect(onSeeAllRecent).toHaveBeenCalledOnce();
});
it("reshuffles the surprise rail alone (refetch) without refetching the surface", async () => {
plexDiscover.mockResolvedValue(fullPayload);
plexSurprise.mockResolvedValue({ scope: "both", items: [card("sp1", "Random Pick")] });
wrap(
<PlexDiscover
scope="both"
onOpenCard={noop}
onInfoCard={noop}
onGenre={noop}
onSeeAllRecent={noop}
/>,
);
await screen.findByText("Random Pick");
expect(plexSurprise).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole("button", { name: "plex.discover.reshuffle" }));
await waitFor(() => expect(plexSurprise).toHaveBeenCalledTimes(2));
expect(plexDiscover).toHaveBeenCalledTimes(1); // the whole surface was NOT refetched
});
it("shows the empty message when every rail is empty", async () => {
plexDiscover.mockResolvedValue({
scope: "both",
continue_watching: [],
recently_added: [],
genres: [],
because_you_watched: null,
});
plexSurprise.mockResolvedValue({ scope: "both", items: [] });
wrap(
<PlexDiscover
scope="both"
onOpenCard={noop}
onInfoCard={noop}
onGenre={noop}
onSeeAllRecent={noop}
/>,
);
await screen.findByText("plex.discover.empty");
});
});
+235
View File
@@ -0,0 +1,235 @@
import { type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { RotateCcw } from "lucide-react";
import { qk } from "../lib/queryKeys";
import { api, type PlexCard, type PlexDiscover as PlexDiscoverData } from "../lib/api";
import { plexLang } from "../i18n";
import { toggleWatchState } from "../lib/plexWatch";
import { Carousel } from "./Carousel";
import { PlexPosterCard } from "./plexCards";
import { LoadingState, StateMessage } from "./QueryState";
// The Plex "Discover" landing (E5 S4): a stack of horizontal Carousel rails served from ONE
// /api/plex/discover call — Continue watching, Recently added, Browse by genre (tiles), Because you
// watched X — plus a separately-fetched, reshuffling Surprise-me rail. The flat browse grid stays its
// own view (PlexBrowse's grid branch); a header search or filter flips the user there. Card click /
// info / watched-toggle handlers come from the shell (PlexBrowse) so a rail card behaves exactly like
// a grid card; the watched-toggle optimistically flips THIS surface's cache too.
// A stable, pleasant hue per genre string (no art to collage yet — colored tiles stand in). Hashing
// keeps a genre the same color across renders/sessions without storing anything.
function genreHue(name: string): number {
let h = 0;
for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) % 360;
return h;
}
function CardRail({
title,
ariaLabel,
seeAllLabel,
onSeeAll,
cards,
onOpenCard,
onInfoCard,
onToggleWatched,
action,
}: {
title: ReactNode;
ariaLabel: string;
seeAllLabel?: string;
onSeeAll?: () => void;
cards: PlexCard[];
onOpenCard: (c: PlexCard) => void;
onInfoCard: (c: PlexCard) => void;
onToggleWatched: (c: PlexCard) => void;
action?: ReactNode; // optional header control (e.g. the Surprise-me reshuffle button)
}) {
const heading =
action != null ? (
<span className="inline-flex items-center gap-2">
{title}
{action}
</span>
) : (
title
);
return (
<section className="mb-8">
<Carousel title={heading} ariaLabel={ariaLabel} onSeeAll={onSeeAll} seeAllLabel={seeAllLabel}>
{cards.map((c) => (
<div key={c.id} className="w-[150px] shrink-0">
<PlexPosterCard
card={c}
onOpen={() => onOpenCard(c)}
onInfo={() => onInfoCard(c)}
onToggleWatched={onToggleWatched}
/>
</div>
))}
</Carousel>
</section>
);
}
export default function PlexDiscover({
scope,
onOpenCard,
onInfoCard,
onGenre,
onSeeAllRecent,
}: {
scope: string;
onOpenCard: (c: PlexCard) => void;
onInfoCard: (c: PlexCard) => void;
onGenre: (genre: string) => void;
onSeeAllRecent: () => void;
}) {
const { t } = useTranslation();
const qc = useQueryClient();
const lang = plexLang();
const q = useQuery({
queryKey: qk.plexDiscover(scope, lang),
queryFn: () => api.plexDiscover(scope, lang),
});
// Surprise-me is its own query so the ↻ button can redraw it without refetching the whole surface.
const surpriseQ = useQuery({
queryKey: qk.plexSurprise(scope),
queryFn: () => api.plexSurprise(scope),
staleTime: 0,
});
// Watched toggle over BOTH this surface's cache (so a rail card flips instantly) and the surprise
// list, then persist + resync via the shared helper — invalidating the grid too so it agrees.
const toggleWatched = (card: PlexCard) =>
toggleWatchState(card, t, {
optimistic: (next) => {
const flip = (cards: PlexCard[]) =>
cards.map((c) => (c.id === card.id ? { ...c, status: next } : c));
qc.setQueryData<PlexDiscoverData>(qk.plexDiscover(scope, lang), (old) =>
old
? {
...old,
continue_watching: flip(old.continue_watching),
recently_added: flip(old.recently_added),
because_you_watched: old.because_you_watched
? { ...old.because_you_watched, items: flip(old.because_you_watched.items) }
: null,
}
: old,
);
qc.setQueryData<{ scope: string; items: PlexCard[] }>(qk.plexSurprise(scope), (old) =>
old ? { ...old, items: flip(old.items) } : old,
);
},
resync: () => {
qc.invalidateQueries({ queryKey: qk.plexDiscover() });
qc.invalidateQueries({ queryKey: qk.plexLibrary() });
},
});
if (q.isError && !q.data) {
return (
<StateMessage tone="error" onRetry={() => q.refetch()}>
{t("common.loadError")}
</StateMessage>
);
}
if (q.isLoading || !q.data) {
return <LoadingState label={t("plex.loading")} />;
}
const d = q.data;
const surprise = surpriseQ.data?.items ?? [];
const bw = d.because_you_watched;
const nothing =
d.continue_watching.length === 0 &&
d.recently_added.length === 0 &&
d.genres.length === 0 &&
surprise.length === 0 &&
(!bw || bw.items.length === 0);
if (nothing) {
return <p className="text-muted text-sm">{t("plex.discover.empty")}</p>;
}
const railProps = { onOpenCard, onInfoCard, onToggleWatched: toggleWatched };
return (
<div>
{d.continue_watching.length > 0 && (
<CardRail
title={t("plex.discover.continueWatching")}
ariaLabel={t("plex.discover.continueWatching")}
cards={d.continue_watching}
{...railProps}
/>
)}
{d.recently_added.length > 0 && (
<CardRail
title={t("plex.discover.recentlyAdded")}
ariaLabel={t("plex.discover.recentlyAdded")}
onSeeAll={onSeeAllRecent}
cards={d.recently_added}
{...railProps}
/>
)}
{surprise.length > 0 && (
<CardRail
title={t("plex.discover.surprise")}
ariaLabel={t("plex.discover.surprise")}
cards={surprise}
action={
<button
type="button"
onClick={() => surpriseQ.refetch()}
aria-label={t("plex.discover.reshuffle")}
title={t("plex.discover.reshuffle")}
className="rounded-full p-1 text-muted transition hover:text-accent"
>
<RotateCcw className={`h-3.5 w-3.5 ${surpriseQ.isFetching ? "animate-spin" : ""}`} />
</button>
}
{...railProps}
/>
)}
{d.genres.length > 0 && (
<section className="mb-8">
<h2 className="mb-3 text-sm font-semibold">{t("plex.discover.byGenre")}</h2>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6">
{d.genres.map((g) => {
const hue = genreHue(g.value);
return (
<button
key={g.value}
type="button"
onClick={() => onGenre(g.value)}
className="glass-hover relative flex h-20 items-end overflow-hidden rounded-xl p-3 text-left transition"
style={{
background: `linear-gradient(135deg, hsl(${hue} 55% 32%), hsl(${(hue + 40) % 360} 60% 22%))`,
}}
>
<span className="text-sm font-semibold text-white drop-shadow">{g.value}</span>
<span className="absolute right-2 top-2 text-2xs text-white/70">{g.count}</span>
</button>
);
})}
</div>
</section>
)}
{bw && bw.items.length > 0 && (
<CardRail
title={t("plex.discover.becauseWatched", { title: bw.anchor.title })}
ariaLabel={t("plex.discover.becauseWatched", { title: bw.anchor.title })}
cards={bw.items}
{...railProps}
/>
)}
</div>
);
}
+4 -2
View File
@@ -5,6 +5,7 @@ import { PLEX_SUB_URL as U, type Sub } from "./plexSubUrl";
describe("PLEX_SUB_URL encode", () => {
it("mirrors each bookmarkable sub-view to ?v=<kind>:<args>", () => {
expect(U.encode({ kind: "grid" })).toBe("browse"); // the flat "Browse all" grid (E5 S4)
expect(U.encode({ kind: "show", id: "s1" })).toBe("show:s1");
expect(U.encode({ kind: "season", showId: "s1", seasonId: "se2" })).toBe("season:s1:se2");
expect(U.encode({ kind: "info", id: "m9" })).toBe("info:m9");
@@ -12,14 +13,15 @@ describe("PLEX_SUB_URL encode", () => {
expect(U.encode({ kind: "playlist", id: 12 })).toBe("playlist:12");
});
it("does NOT mirror the root grid or the ephemeral player (encode → null)", () => {
expect(U.encode({ kind: "grid" })).toBeNull();
it("does NOT mirror the root Discover landing or the ephemeral player (encode → null)", () => {
expect(U.encode({ kind: "discover" })).toBeNull();
expect(U.encode({ kind: "player", id: "m9" })).toBeNull();
});
});
describe("PLEX_SUB_URL round-trip", () => {
const cases: Sub[] = [
{ kind: "grid" },
{ kind: "show", id: "s1" },
{ kind: "season", showId: "s1", seasonId: "se2" },
{ kind: "info", id: "m9" },
+10 -3
View File
@@ -5,6 +5,7 @@ import { parsePositiveIntId } from "../lib/parseId";
// encode/decode round-trip (and its guards) can be unit-tested without pulling the whole component
// (and its lazy hls.js player) into the test graph.
export type Sub =
| { kind: "discover" }
| { kind: "grid" }
| { kind: "show"; id: string }
| { kind: "season"; showId: string; seasonId: string }
@@ -14,12 +15,16 @@ export type Sub =
| { kind: "playlist"; id: number };
// Mirror the Plex sub-view to ?v=<kind>:<args> so a show / season / movie-info / person / playlist page
// is bookmarkable. Grid (root) and the ephemeral player are not mirrored (encode → null). The person
// name is the whole tail after the first ":", so a name containing ":" round-trips.
// — and the flat browse grid — are bookmarkable. Discover is the ROOT landing (E5 S4), so it (and the
// ephemeral player) is not mirrored (encode → null); the grid gets `?v=browse` so "Browse all" is a
// distinct, shareable URL. The person name is the whole tail after the first ":", so a name containing
// ":" round-trips.
export const PLEX_SUB_URL: SubviewUrl<Sub> = {
key: "v",
encode: (v) => {
switch (v.kind) {
case "grid":
return "browse";
case "show":
return `show:${v.id}`;
case "season":
@@ -31,7 +36,7 @@ export const PLEX_SUB_URL: SubviewUrl<Sub> = {
case "playlist":
return `playlist:${v.id}`;
default:
return null; // grid + the ephemeral player are not URL-mirrored
return null; // discover (root) + the ephemeral player are not URL-mirrored
}
},
decode: (raw) => {
@@ -39,6 +44,8 @@ export const PLEX_SUB_URL: SubviewUrl<Sub> = {
const kind = i === -1 ? raw : raw.slice(0, i);
const arg = i === -1 ? "" : raw.slice(i + 1);
switch (kind) {
case "browse":
return { kind: "grid" };
case "show":
return arg ? { kind: "show", id: arg } : null;
case "info":