refactor(player): one panel at a time over the Plex video, and one Back cascade

The ⋯ menu, the tracks menu, the tuning panel, the info overlay and the up-next card were a flag
each, so two could stand on top of each other, and Back/Escape were written out three times. They
are one `panel` value now; the stats readout stays a separate toggle beside it. One `back()` peels
the countdown, the panel, then the stats, then leaves — for the arrow, ⌫, Escape and the mouse
Back alike. The mouse Back now also closes the ⋯ menu instead of leaving the player.
This commit is contained in:
2026-10-06 23:04:35 +02:00
parent c1058f1d5a
commit 02feaa9a1c
2 changed files with 226 additions and 90 deletions
@@ -0,0 +1,160 @@
// @vitest-environment jsdom
//
// What may be open over the Plex player at once, and what Back closes. The ⋯ menu, the tracks
// menu, the tuning panel, the info overlay and the up-next card are ONE value: opening one replaces
// the other, so two can never draw on top of each other. The stats readout is not one of them — it
// stays up beside a panel — and every "back" (⌫, Escape, the mouse/browser Back) peels the panel
// first, then the stats, and only then leaves the player.
import { describe, it, expect, vi, beforeAll, afterEach } from "vitest";
import { render, cleanup, waitFor, act, screen, fireEvent } 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" } }),
}));
import PlexPlayer from "./PlexPlayer";
import { api, type PlexItemDetail } 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;
for (const [name, value] of Object.entries({
play: () => Promise.resolve(),
pause: () => {},
load: () => {},
}))
Object.defineProperty(HTMLMediaElement.prototype, name, { configurable: true, value });
Object.defineProperty(HTMLMediaElement.prototype, "seekable", {
configurable: true,
get: () => ({ length: 0, end: () => 0 }),
});
Object.defineProperty(HTMLMediaElement.prototype, "textTracks", {
configurable: true,
get: () => Object.assign([], { addEventListener() {}, removeEventListener() {} }),
});
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
const detail = {
id: "1",
title: "Title 1",
type: "movie",
duration_seconds: 3000,
status: "new",
position_seconds: 0,
audio_streams: [],
subtitle_streams: [],
markers: [],
cast: [],
genres: [],
} as unknown as PlexItemDetail;
async function mount() {
vi.spyOn(api, "plexItem").mockResolvedValue(detail);
vi.spyOn(api, "plexSession").mockResolvedValue({
mode: "direct",
url: "/media/1",
start_s: 0,
} as Awaited<ReturnType<typeof api.plexSession>>);
vi.spyOn(api, "plexProgress").mockResolvedValue(undefined as never);
const onClose = vi.fn();
render(
<QueryClientProvider
client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}
>
<PlexPlayer itemId="1" onClose={onClose} />
</QueryClientProvider>,
);
await waitFor(() =>
expect(document.querySelector("video")?.getAttribute("src")).toBe("/media/1"),
);
return onClose;
}
const press = (key: string) =>
act(() => {
window.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
});
// `hidden`: the faded-out control bands are aria-hidden while the video plays.
const settings = () => screen.queryByRole("dialog", { name: "plex.player.settings", hidden: true });
const stats = () => screen.queryByRole("region", { name: "plex.player.stats.title", hidden: true });
const moreMenu = () => screen.queryByRole("menu", { hidden: true });
// The info overlay is the full-screen scrim the media info sits in.
const info = () => document.querySelector(".place-items-center.z-menu");
async function openSettings() {
fireEvent.click(screen.getByLabelText("plex.player.more"));
const row = await waitFor(() => {
const r = screen
.queryAllByRole("menuitem", { hidden: true })
.find((b) => b.textContent === "plex.player.settings");
expect(r).toBeDefined();
return r!;
});
fireEvent.click(row);
await waitFor(() => expect(settings()).not.toBeNull());
}
describe("PlexPlayer · one panel at a time", () => {
it("the browser Back with the ⋯ menu open closes the menu, not the player", async () => {
const onClose = await mount();
fireEvent.click(screen.getByLabelText("plex.player.more"));
await waitFor(() => expect(moreMenu()).not.toBeNull());
// The menu claims a history entry, so the Back below is spent on it. First in the file: the
// history module's entry count is per module, and an earlier test's entries would be in it.
await waitFor(() => expect(window.history.state?._ov).toBeDefined());
await act(async () => {
const landed = new Promise((resolve) =>
window.addEventListener("popstate", resolve, { once: true }),
);
window.history.back();
await landed;
});
await waitFor(() => expect(moreMenu()).toBeNull());
expect(onClose).not.toHaveBeenCalled();
});
it("the info overlay replaces the tuning panel rather than drawing over it", async () => {
await mount();
await openSettings();
press("i");
await waitFor(() => expect(info()).not.toBeNull());
expect(settings()).toBeNull();
});
it("the stats readout stays up beside a panel; Escape peels the panel, then the stats, then leaves", async () => {
const onClose = await mount();
press("d");
press("i");
await waitFor(() => expect(info()).not.toBeNull());
expect(stats()).not.toBeNull();
press("Escape");
expect(info()).toBeNull();
expect(stats()).not.toBeNull();
expect(onClose).not.toHaveBeenCalled();
press("Escape");
expect(stats()).toBeNull();
expect(onClose).not.toHaveBeenCalled();
press("Escape");
expect(onClose).toHaveBeenCalledTimes(1);
});
});
+66 -90
View File
@@ -128,6 +128,7 @@ const DOUBLE_TAP_MS = 300;
// `fromStart` (the card's Restart, C5) applies to the item the player opened with; every item it
// moves on to starts at its own resume point.
type Props = { itemId: string; onClose: () => void; queue?: string[]; fromStart?: boolean };
type Panel = "none" | "more" | "tracks" | "settings" | "info" | "upNext";
export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }: Props) {
const { t, i18n } = useTranslation();
@@ -253,15 +254,23 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
const langPrefsRef = useLatest({ audioLang: prefs.audioLang, subLang: prefs.subLang });
const seekStepRef = useLatest(prefs.seekStep);
const fineSeekStepRef = useLatest(prefs.fineSeekStep);
const [menuOpen, setMenuOpen] = useState(false); // the tuning panel (tabbed), from ⋯ → Settings
// The fixed ⋯ (C5): the rare tools — settings, media info, stats, shortcuts, the original file.
const [moreOpen, setMoreOpen] = useState(false);
const [tracksOpen, setTracksOpen] = useState(false); // separate quick menu = audio/subtitle tracks
// What is open over the video, one at a time: the fixed ⋯ (C5, the rare tools), the quick tracks
// menu, the tabbed tuning panel (from ⋯ → Settings), the rich info overlay ("I") and the up-next
// end-card. One value rather than a flag each, so two of them can never stand on top of each
// other and Back/Escape have exactly one thing to close. The stats readout ("D") is not in it: a
// corner readout, not a panel, which stays up beside them (the sync offset is tuned watching it).
const [panel, setPanel] = useState<Panel>("none");
const panelRef = useLatest(panel);
const infoOpenRef = useLatest(panel === "info"); // the wheel is the overlay's scroll, not volume
// A panel closes only itself: a popover's late "closed" must not shut the panel that replaced it.
const closePanel = useCallback((p: Panel) => setPanel((cur) => (cur === p ? "none" : cur)), []);
const togglePanel = useCallback((p: Panel) => setPanel((cur) => (cur === p ? "none" : p)), []);
// The tuning panel's tab outlives its closing: it reopens where it was left.
const [settingsTab, setSettingsTab] = useState<"sync" | "playback" | "subtitle" | "clock">(
"sync",
);
// keep the control bar up while one is open
const menuOpenRef = useLatest(menuOpen || tracksOpen || moreOpen);
// keep the control bar up while a menu is open
const menuOpenRef = useLatest(panel === "more" || panel === "tracks" || panel === "settings");
const menuRef = useRef<HTMLDivElement>(null);
const menuTriggerRef = useRef<HTMLButtonElement | null>(null);
// Auto-hiding control bar (reveal on mouse move / any key; hide after 3s while playing).
@@ -293,17 +302,17 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
// The tuning panel stays open until a click/Escape OUTSIDE it (so sliders can be dragged freely).
// It renders inside the player, whose Tab trap spans it; the ⋯ counts as inside, since the ⋯ is
// what closes it (below).
useDismiss(menuOpen, () => setMenuOpen(false), [menuRef, menuTriggerRef]);
useDismiss(panel === "settings", () => closePanel("settings"), [menuRef, menuTriggerRef]);
// The ⋯ and the tracks list are real menus on the popover engine: roving arrows,
// Home/End, Escape as a layer, and the focus back on the trigger however they close. They were
// hand-built <div>s — no roles, no arrows, and Escape left the focus on <body>. The engine portals
// them into the fullscreen element when there is one, so they show in fullscreen too.
const morePop = useAnchoredPopover({
open: moreOpen,
open: panel === "more",
// The ⋯ also CLOSES the tuning panel it opened, rather than stacking the menu over it.
onOpenChange: (open) => {
if (open && menuOpen) setMenuOpen(false);
else setMoreOpen(open);
if (!open) closePanel("more");
else setPanel((cur) => (cur === "settings" ? "none" : "more"));
},
placement: "top-end",
offset: 8,
@@ -311,8 +320,8 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
openOnArrowKey: false,
});
const tracksPop = useAnchoredPopover({
open: tracksOpen,
onOpenChange: setTracksOpen,
open: panel === "tracks",
onOpenChange: (open) => (open ? setPanel("tracks") : closePanel("tracks")),
placement: "top-end",
offset: 8,
fitHeight: true,
@@ -352,15 +361,9 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
},
[],
);
// "I" toggles a rich info overlay (poster/cast/ratings) over the running video.
const [infoOpen, setInfoOpen] = useState(false);
const infoOpenRef = useLatest(infoOpen);
// "D" toggles the stats-for-nerds debug overlay (active mode, codec, dropped frames, buffer…).
const [statsOpen, setStatsOpen] = useState(false);
const statsOpenRef = useLatest(statsOpen);
// Up-next end-card: shown at episode end (with a next item) instead of an instant jump.
const [upNextOpen, setUpNextOpen] = useState(false);
const upNextOpenRef = useLatest(upNextOpen);
const upNextPrefRef = useLatest(prefs.upNext);
const now = useWallClock();
@@ -756,13 +759,13 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
id: "settings",
label: t("plex.player.settings"),
icon: <Settings className={ico} />,
run: () => setMenuOpen(true),
run: () => setPanel("settings"),
},
{
id: "info",
label: t("plex.player.infoBtn"),
icon: <Info className={ico} />,
run: () => setInfoOpen((v) => !v),
run: () => togglePanel("info"),
},
]
: []),
@@ -802,7 +805,7 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
// With a next item and the up-next pref on, surface the end-card (poster + countdown + Cancel)
// and let IT advance — binge stays in the viewer's control. The card only appears here,
// on play-to-the-end; credits-auto-skip advances earlier and this handler never fires for it.
if (nextId && upNextPrefRef.current) setUpNextOpen(true);
if (nextId && upNextPrefRef.current) setPanel("upNext");
else if (nextId) go(nextId);
// Nothing queued next → dismiss the player back to the previous page (same as Stop/Escape),
// instead of stranding a black, ended <video> on screen.
@@ -815,45 +818,35 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
// Up-next card actions: advance = go to the next item (it was already marked watched on 'ended');
// cancel = dismiss and stay on the finished frame. Loading a new item closes any lingering card.
const advanceUpNext = useCallback(() => {
setUpNextOpen(false);
closePanel("upNext");
if (nextId) go(nextId);
}, [nextId, go]);
}, [nextId, go, closePanel]);
// The "up next" card belongs to the item that was playing, so a queue advance closes it. Adjusted
// during the render that changes `id` rather than in an effect: as an effect it closed one commit
// after the new episode had already drawn behind it.
const [upNextForId, setUpNextForId] = useState(id);
if (upNextForId !== id) {
setUpNextForId(id);
setUpNextOpen(false);
closePanel("upNext");
}
// "Back" cascade shared by the on-screen Back arrow AND the keyboard/remote Backspace·Escape: peel
// off whatever is layered on top (a tuning/tracks menu, then the info overlay) before leaving the
// player. The arrow used to call onClose() unconditionally, so Back with the info panel open
// jumped straight to the feed instead of just closing the panel. The shortcuts sheet is no longer
// in this cascade: it is a Modal above us now, and owns its own Escape layer and Back-to-close.
const handleBack = useCallback(() => {
if (menuOpenRef.current) {
setMenuOpen(false);
setTracksOpen(false);
setMoreOpen(false);
} else if (infoOpenRef.current) setInfoOpen(false);
else if (statsOpenRef.current) setStatsOpen(false);
else if (upNextOpenRef.current) setUpNextOpen(false);
else onClose();
}, [onClose, menuOpenRef, infoOpenRef, statsOpenRef, upNextOpenRef]);
// The mouse "back" button (and the browser Back) fire history popstate — which would pop the whole
// player subview and drop straight to the grid, even with a panel or an auto-skip countdown up.
// While any of those is showing we register a history entry (BackClose below) whose Back handler
// runs this: cancel the countdown, else close the topmost panel — matching ⌫ / Esc exactly.
const backIntent = useCallback(() => {
if (skipProgressRef.current != null) {
cancelAutoSkipRef.current();
return;
}
handleBack();
}, [handleBack, skipProgressRef, cancelAutoSkipRef]);
// The ONE Back cascade, for every way of saying "back": the on-screen arrow, ⌫, Escape, and the
// mouse/browser Back (history popstate, through BackClose below). It peels off what is layered
// over the video — the auto-skip countdown, then the open panel, then the stats readout — and only
// then leaves the player. The shortcuts sheet is not in it: a Modal above us, with its own Escape
// layer and Back-to-close.
// - The on-screen arrow is a click on "leave", not a cancel, so it does not stop a countdown.
// - Escape in fullscreen leaves fullscreen (the browser's own Escape) and not the player.
const back = useCallback(
(from: "arrow" | "key" | "history" | "escape") => {
if (from !== "arrow" && skipProgressRef.current != null) cancelAutoSkipRef.current();
else if (panelRef.current !== "none") setPanel("none");
else if (statsOpenRef.current) setStatsOpen(false);
else if (from !== "escape" || !fullscreenElement()) onClose();
},
[onClose, panelRef, statsOpenRef, skipProgressRef, cancelAutoSkipRef],
);
const backFromHistory = useCallback(() => back("history"), [back]);
// Tell the shared cheat sheet which keys are live here, and whether ⇧← / ⇧→ apply (they step
// episodes, so they are listed only inside a series).
@@ -968,7 +961,7 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
: "—";
flashOsd(`${t("plex.player.subtitles")} · ${label}`);
},
info: () => setInfoOpen((v) => !v),
info: () => togglePanel("info"),
stats: () => setStatsOpen((v) => !v),
back: (ev) => {
// HTPC-style "stop & go back" to wherever the player was opened from — mirrors the mouse
@@ -980,19 +973,13 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
// (the first fix, the second bug — the player's OWN gear/tracks popovers push layers too, so
// ⌫ stopped closing them), then naming just the sheet and palette (the second fix, the third
// bug — the app-wide ErrorDialog is neither, so ⌫ tore the player down under it).
// The rule that holds: the player's own panels answer first, because `handleBack`'s cascade
// is what closes them; anything else layered above us takes the key.
const ownPanelOpen =
menuOpenRef.current ||
infoOpenRef.current ||
statsOpenRef.current ||
upNextOpenRef.current;
// The rule that holds: the player's own panels answer first, because `back`'s cascade is
// what closes them; anything else layered above us takes the key.
const ownPanelOpen = panelRef.current !== "none" || statsOpenRef.current;
if (!ownPanelOpen && layerIdRef.current != null && anyLayerAbove(layerIdRef.current))
return;
ev.preventDefault();
if (skipProgressRef.current != null)
cancelAutoSkipRef.current(); // cancel auto-skip, don't go back
else handleBack();
back("key");
},
escape: (ev) => {
// Defer to any layer opened above the player (Modal or anchored popover) — let it take the
@@ -1002,15 +989,7 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
// one and its close can pop it off the stack synchronously, so `anyLayerAbove` alone misses it.
if (escapeHandled(ev)) return;
if (layerIdRef.current != null && anyLayerAbove(layerIdRef.current)) return;
if (skipProgressRef.current != null) cancelAutoSkipRef.current();
else if (menuOpenRef.current) {
setMenuOpen(false);
setTracksOpen(false);
setMoreOpen(false);
} else if (infoOpenRef.current) setInfoOpen(false);
else if (statsOpenRef.current) setStatsOpen(false);
else if (upNextOpenRef.current) setUpNextOpen(false);
else if (!fullscreenElement()) onClose();
back("escape");
},
});
};
@@ -1034,16 +1013,13 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
onClose,
wake,
controlsShown,
handleBack,
skipProgressRef,
cancelAutoSkipRef,
back,
togglePanel,
engine,
seekStepRef,
fineSeekStepRef,
menuOpenRef,
infoOpenRef,
panelRef,
statsOpenRef,
upNextOpenRef,
]);
// Seekbar hover: a timestamp tooltip that follows the cursor. Store the position as a FRACTION
@@ -1223,8 +1199,8 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
{/* While a panel/menu is open or an auto-skip countdown is running, take over the browser/mouse
Back button (history popstate) so it closes/cancels that instead of dropping to the grid. */}
{(menuOpen || tracksOpen || infoOpen || statsOpen || upNextOpen || skipProgress != null) && (
<BackClose onBack={backIntent} />
{(panel !== "none" || statsOpen || skipProgress != null) && (
<BackClose onBack={backFromHistory} />
)}
{/* Top bar */}
@@ -1241,7 +1217,7 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
variant="overlay"
size="player"
round
onClick={handleBack}
onClick={() => back("arrow")}
label={t("plex.player.back")}
>
<ArrowLeft />
@@ -1484,7 +1460,7 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
round
ref={setTracksReference}
{...tracksPop.getReferenceProps()}
aria-expanded={tracksOpen}
aria-expanded={panel === "tracks"}
label={t("plex.player.tracks")}
>
<Languages />
@@ -1570,7 +1546,7 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
round
ref={moreTriggerRef}
{...morePop.getReferenceProps()}
aria-expanded={moreOpen || menuOpen}
aria-expanded={panel === "more" || panel === "settings"}
label={t("plex.player.more")}
>
<MoreHorizontal />
@@ -1588,7 +1564,7 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
label={it.label}
// Closes first, so the focus is back on the ⋯ before the tool opens: a dialog
// opened from here returns the focus to where it found it.
onSelect={() => closeThenAct(() => setMoreOpen(false), it.run)}
onSelect={() => closeThenAct(() => closePanel("more"), it.run)}
className={`${PLAYER_ROW} flex min-h-9 items-center gap-2.5 text-white`}
>
{it.icon}
@@ -1597,7 +1573,7 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
))}
</div>
</PopoverSurface>
{menuOpen && (
{panel === "settings" && (
<PlexPlayerSettings
menuRef={menuRef}
returnFocusTo={menuTriggerRef}
@@ -1642,21 +1618,21 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
{/* Up-next end-card (episode end, next item queued, pref on). Non-modal — the finished frame
stays behind it; the card's own countdown advances unless the viewer cancels. */}
{upNextOpen && nextId && (
{panel === "upNext" && nextId && (
<UpNextCard
nextId={nextId}
onAdvance={advanceUpNext}
onCancel={() => setUpNextOpen(false)}
onCancel={() => closePanel("upNext")}
/>
)}
{/* Rich info overlay (poster/cast/ratings) — "i" or the info button; video keeps playing. */}
{infoOpen && detail && (
{panel === "info" && detail && (
<div
className="absolute inset-0 z-menu grid place-items-center overflow-y-auto bg-black/70 p-4"
onClick={(e) => {
e.stopPropagation();
setInfoOpen(false);
closePanel("info");
}}
>
<div
@@ -1667,10 +1643,10 @@ export default function PlexPlayer({ itemId, onClose, queue, fromStart = false }
<PlexInfo
detail={detail}
variant="overlay"
onClose={() => setInfoOpen(false)}
onClose={() => closePanel("info")}
// A collection sibling plays right here, as Next would.
onPlayItem={(other, fromZero) => {
setInfoOpen(false);
closePanel("info");
go(other, undefined, fromZero);
}}
/>