feat(player): a bookmark reopens every player as it was, once

The Plex player names the playlist it plays through (v=player:<id>:playlist:<pid>), so a bookmark
rebuilds the queue from the playlist's own order while the item is still in it.

Found in the browser and fixed:
- after a reload the shell's player opened a second one over Home and the feed: it read the catalog
  row the page had fetched (a disabled query still reads the shared cache); it now waits for ready.
- every reload under an open overlay left a dead history step: the first overlay to open takes over
  the entry the document was loaded on.
- the feed's address was implicit, the same as the start-page landing, so a reloaded or bookmarked
  feed opened as Home: the feed now names itself (page=feed) like every page.
- a linked file or video that is gone was said, but stayed in the address and was said again on
  every reload: its keys are taken off.

The overlay address is written in one place (the entry is named once it is current), and the player
keys only the codec reads are no longer exported.
This commit is contained in:
2026-10-27 07:33:55 +01:00
parent fa893c73a3
commit 3d26ca0efa
23 changed files with 343 additions and 53 deletions
@@ -231,7 +231,7 @@ describe("NavigationProvider · a link carrying another page's keys", () => {
it("opens a channel link with only the channel page's keys, even over the page they belong to", () => {
window.history.replaceState({}, "", "/?q=music&sort=oldest&chan=UC1&chtab=about&chtypes=ns");
render();
expect(window.location.search).toBe("?chan=UC1&chtab=about&chtypes=ns");
expect(window.location.search).toBe("?chan=UC1&chtab=about&chtypes=ns&page=feed");
});
});
@@ -242,10 +242,10 @@ describe("NavigationProvider · the channel page's address", () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?q=music&sort=oldest");
const { result } = render();
act(() => result.current.openChannel("UC1", "One"));
expect(window.location.search).toBe("?chan=UC1");
expect(window.location.search).toBe("?page=feed&chan=UC1");
act(() => window.history.back());
await vi.waitFor(() => expect(result.current.channelView).toBeNull());
expect(window.location.search).toBe("?q=music&sort=oldest");
expect(window.location.search).toBe("?q=music&sort=oldest&page=feed");
});
it("says no page owns the address while the channel stands over it", () => {
@@ -277,7 +277,7 @@ describe("NavigationProvider · the channel page's address", () => {
const { result } = render();
stubNavigation([false]);
act(() => result.current.closeChannel());
expect(window.location.search).toBe("");
expect(window.location.search).toBe("?page=feed");
});
});
@@ -293,7 +293,7 @@ describe("NavigationProvider · the player's address", () => {
it("a channel link names no player: opening the channel closes it", () => {
window.history.replaceState({}, "", "/?q=music&watch=v1&wrel=v2&wtab=related");
render();
expect(channelUrl("UC1")).toBe("/?chan=UC1");
expect(channelUrl("UC1")).toBe("/?page=feed&chan=UC1");
});
});
@@ -310,7 +310,7 @@ describe("NavigationProvider · Back", () => {
expect(result.current.page).toBe("feed");
// …and the entry says so too, so the address bar and a later Feed click agree with the screen.
expect(window.history.state).toMatchObject({ sfPage: "feed" });
expect(window.location.search).toBe("?keep=1");
expect(window.location.search).toBe("?page=feed&keep=1");
});
it("lands where a retired page's content went, and the entry names that page", () => {
@@ -427,7 +427,7 @@ describe("NavigationProvider · a page the account cannot open", () => {
window.history.replaceState(null, "", "/?page=scheduler&keep=1");
const { result } = render();
expect(result.current.page).toBe("feed");
expect(window.location.search).toBe("?keep=1");
expect(window.location.search).toBe("?page=feed&keep=1");
expect(window.history.state).toMatchObject({ sfPage: "feed" });
});
@@ -463,7 +463,7 @@ describe("NavigationProvider · a page the account cannot open", () => {
qc.setQueryData(qk.me(), member);
});
await settle();
expect(window.location.search).toBe("");
expect(window.location.search).toBe("?page=feed");
expect(window.history.state).toMatchObject({ sfPage: "feed" });
expect(getAccountRaw(PAGE_KEY)).toBe("feed");
act(() => {
@@ -483,7 +483,7 @@ describe("NavigationProvider · a page the account cannot open", () => {
});
await settle();
expect(result.current.channelView).toBeNull();
expect(window.location.search).toBe("");
expect(window.location.search).toBe("?page=feed");
expect(window.history.state?._chan).toBeUndefined();
});
});
@@ -44,12 +44,13 @@ import {
//
// The contexts, their value types and the hooks live in navigationContext.ts.
/** The address bar of `page`'s root: the page (feed implicit), no channel or player over it, and every
* module's own keys cleared — a page switch resets to that module's root, and its store mirrors what
* it holds back in. */
/** The address bar of `page`'s root: the page — the feed too: a bare address is the landing (Home, or
* the remembered page), so a feed left unnamed reloaded or bookmarked as another page — no channel or
* player over it, and every module's own keys cleared — a page switch resets to that module's root,
* and its store mirrors what it holds back in. */
function pageRootParams(page: Page): Record<string, string | null> {
return {
page: page === "feed" ? null : page,
page,
...closedChannelParams(),
...nulls(PLAYER_KEYS),
...nulls(moduleUrlKeys()),
@@ -126,7 +127,7 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
setAccountRaw(PAGE_KEY, next);
// Push an in-app history entry so browser/mouse Back steps through pages instead of leaving
// the app. A fresh { sfPage } (no carried-over _yt/_chan markers) so each page starts at its
// root, and the address bar reflects the page (feed is implicit) while clearing `chan` and
// root, and the address bar reflects the page (the feed too) while clearing `chan` and
// every module's own keys (pageRootParams) — a page switch resets to that module's root, and
// each module's store mirrors its state back in on its page. The item it was opened from is
// still focused: the state setters above have not re-rendered anything yet.
@@ -247,7 +248,7 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
// so it restores and re-fetches free (ytSearch above already initialised from it). _chan/_chanName
// are always kept so a channel page survives F5.
const st = window.history.state || {};
// Mirror the resolved initial page to the address bar (feed implicit) so a page reached from the
// Mirror the resolved initial page to the address bar (the feed too) so a page reached from the
// stored landing pref — not just from the URL — is itself bookmarkable. urlWithParams preserves any
// ?chan / ?v / ?pl / filter params the loaders already read.
// A retired page's link — or the remembered last page, when that is what opened — also opens its
@@ -261,7 +262,7 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
const url = urlWithParams({
...nulls(shown ? moduleUrlKeys() : foreignUrlKeys(mountPage)),
...retiredParams(linked ?? (resolvePage(remembered) === mountPage ? remembered : null)),
page: mountPage === "feed" ? null : mountPage,
page: mountPage,
});
if (st._yt && st._ytScrape) {
window.history.replaceState({ ...st, sfPage: mountPage }, "", url);
@@ -282,7 +283,7 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
window.history.replaceState(
{ ...window.history.state, sfPage: p },
"",
urlWithParams({ ...retiredParams(sf), page: p === "feed" ? null : p }),
urlWithParams({ ...retiredParams(sf), page: p }),
);
setPageState(p);
setAccountRaw(PAGE_KEY, p);
@@ -165,6 +165,22 @@ describe("the player's address", () => {
expect(window.location.search).toBe("");
});
it("a link's related video that arrives after the queue stepped on stays off the next item", async () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?watch=A&wrel=rel2");
let arrive: (v: Video) => void = () => {};
vi.spyOn(api, "videoRow").mockReturnValue(new Promise<Video>((r) => (arrive = r)));
const r = renderModal(vid("A"), [vid("A"), vid("B")]);
fireEvent.click(screen.getAllByRole("button", { name: "player.next" })[0]!);
await waitFor(() => expect(here().get("watch")).toBe("B"));
await act(async () => {
arrive(vid("rel2", 120));
await new Promise((r) => setTimeout(r, 50)); // the query hands its answer on a tick later
});
expect(screen.getByRole("heading", { name: "Video B" })).toBeTruthy();
expect(here().has("wrel")).toBe(false);
await closeAndLand(r.unmount);
});
it("wide: a link naming another item brings none of its view", async () => {
wideWindow();
window.history.replaceState({ sfPage: "feed" }, "", "/?watch=Z&wrel=rel2&wtab=related");
@@ -26,6 +26,7 @@ import { useOpenLinkedPlayer } from "./useOpenLinkedPlayer";
import { LinkedPlayer } from "./LinkedPlayer";
import { api, type Video } from "../../lib/api";
import { notifyActionError } from "../../lib/actionErrors";
import { qk } from "../../lib/queryKeys";
const vid = (id: string) => ({ id, title: id }) as unknown as Video;
@@ -48,13 +49,14 @@ describe("useOpenLinkedPlayer", () => {
const open = vi.fn();
const list = [vid("A"), vid("B")];
const { rerender } = renderHook(
({ ready }) => useOpenLinkedPlayer(ready, (id) => list.find((v) => v.id === id), open),
{ wrapper, initialProps: { ready: false } },
({ ready, rows }) => useOpenLinkedPlayer(ready, (id) => rows.find((v) => v.id === id), open),
{ wrapper, initialProps: { ready: false, rows: list } },
);
expect(open).not.toHaveBeenCalled();
rerender({ ready: true });
rerender({ ready: true, rows: list });
await waitFor(() => expect(open).toHaveBeenCalledWith(list[1], true));
rerender({ ready: true });
// The list refetched (new rows for the same videos): the player it opened is not opened again.
rerender({ ready: true, rows: [vid("A"), vid("B")] });
expect(open).toHaveBeenCalledTimes(1);
expect(row).not.toHaveBeenCalled();
});
@@ -77,6 +79,8 @@ describe("useOpenLinkedPlayer", () => {
expect(notifyActionError).toHaveBeenCalledWith(gone, "player.linkedFailed"),
);
expect(open).not.toHaveBeenCalled();
// Said once: the address no longer names it, so a reload or a copied link does not say it again.
expect(new URLSearchParams(window.location.search).has("watch")).toBe(false);
});
it("opens nothing, and asks for nothing, for an address that names no player", async () => {
@@ -98,6 +102,20 @@ describe("the shell's LinkedPlayer", () => {
expect(await screen.findByText("playing Z alone")).toBeTruthy();
});
it("leaves it to a page that hosts its own, even once that page has fetched the row", async () => {
// The page plays it alone, from the catalog row it asked for: the same cache entry this one reads.
window.history.replaceState(null, "", "/?page=home&watch=Z");
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
qc.setQueryData(qk.videoRow("Z"), vid("Z"));
render(
<QueryClientProvider client={qc}>
<LinkedPlayer hosted />
</QueryClientProvider>,
);
await new Promise((r) => setTimeout(r, 20));
expect(screen.queryByText(/playing/)).toBeNull();
});
it("leaves it to a page that hosts its own", async () => {
window.history.replaceState(null, "", "/?watch=Z");
const row = vi.spyOn(api, "videoRow").mockResolvedValue(vid("Z"));
@@ -3,7 +3,8 @@ import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import { api, type Video } from "../../lib/api";
import { qk } from "../../lib/queryKeys";
import { linkedPlayer } from "../../lib/playerUrlState";
import { linkedPlayer, PLAYER_KEYS } from "../../lib/playerUrlState";
import { dropFromAddress } from "../../lib/urlState";
import { notifyActionError } from "../../lib/actionErrors";
/** Opens the player an address names (a reload, a bookmark — lib/playerUrlState) on the page that
@@ -27,13 +28,19 @@ export function useOpenLinkedPlayer(
retry: false,
});
const openIt = useEffectEvent(open);
const failed = useEffectEvent((err: unknown) => notifyActionError(err, t("player.linkedFailed")));
const failed = useEffectEvent((err: unknown) => {
notifyActionError(err, t("player.linkedFailed"));
dropFromAddress(PLAYER_KEYS);
});
useEffect(() => {
if (done.current) return;
// Not before the host is ready: the row's cache entry is shared, so another opener's fetch fills
// it here too (a disabled query still reads the cache) — the shell's player over a page that
// plays its own would open a second one.
if (done.current || !ready) return;
if (listed) openIt(listed, true);
else if (row.data) openIt(row.data, false);
else if (row.isError) failed(row.error);
else return;
done.current = true;
}, [listed, row.data, row.isError, row.error]);
}, [ready, listed, row.data, row.isError, row.error]);
}