fix(nav): a linked player, file and search survive what the app does by itself (review round 2)

- Playlists: a link over a playlist the account does not hold plays alone; the rail's own
  fallback no longer counts as a pick that gives the player up.
- The linked opener opens or clears nothing once the address names another player, and stops
  looking (and fetching its row) once it settled.
- Files: a list the server's cap cut — the sorted or searched one too — keeps the link, with a
  notice of its own (EN/HU).
- History: an in-place view rewrite (search refine, count, channel to channel, sub-view)
  drops a reloaded entry's overlay marks (replaceView); a landing on a channel opened from a
  search keeps the search; the Feed press on a search opens the plain feed.
- Files/Playlists: an emptied search is written at once.
- Client log: plf/cf (column text filters) are typed keys; the shell has none of its own.
- Contract: writers outside lib/ take a literal or a lib/ function's result; every URL key is
  sorted typed or not; the writer regexes are held by a fixture; sub-views named; the bookmark
  net reads page tags.
- Feed defaults in one constant; one live-search queue helper; Scheduler writes through the
  Activity codec; notRun copy (EN/HU) names Forward and a plain "Search YouTube" button.
This commit is contained in:
2026-10-27 16:08:52 +01:00
parent 0d5c6273f1
commit 6d57d62ac8
38 changed files with 717 additions and 187 deletions
@@ -0,0 +1,57 @@
// @vitest-environment jsdom
//
// A reload under a dialog that does not reopen (About) loads on the dialog's entry, its overlay mark
// still on it. A view rewritten in place there (the search refined) is another view: the next overlay
// pushes its own entry over it rather than taking this one over — taken over, closing it stepped back
// onto the entry below, and the screen went back to the search before the refine. Its own file: the
// entry is read as the history module loads, so it is set up before the import.
import { describe, expect, it, vi } from "vitest";
import { act, renderHook } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
vi.mock("react-i18next", async (importOriginal) => ({
...(await importOriginal<typeof import("react-i18next")>()),
useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),
}));
describe("a view rewritten in place on the entry a reload under a dialog started from", () => {
it("is where an overlay over it closes to", async () => {
window.history.replaceState({ sfPage: "feed", _yt: "dogs" }, "", "/?page=feed&yt=dogs");
window.history.pushState(
{ sfPage: "feed", _yt: "dogs", _ov: 1, _ovd: 1 },
"",
"/?page=feed&yt=dogs",
);
const { NavigationProvider } = await import("./NavigationProvider");
const { useNavigation, useNavigationActions } = await import("./navigationContext");
const { useBackToClose } = await import("../../lib/history");
const { qk } = await import("../../lib/queryKeys");
const { claimLocalData } = await import("../../lib/storage");
const qc = new QueryClient();
qc.setQueryData(qk.me(), { id: 1, role: "admin" });
claimLocalData(1);
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={qc}>
<NavigationProvider>{children}</NavigationProvider>
</QueryClientProvider>
);
const nav = renderHook(() => ({ ...useNavigation(), ...useNavigationActions() }), { wrapper });
act(() => nav.result.current.enterYtSearch("cats"));
const depth = window.history.length;
const overlay = renderHook(() => useBackToClose(() => {}));
await act(async () => {
await Promise.resolve();
});
expect(window.history.length).toBe(depth + 1);
await act(async () => {
const landed = new Promise((res) => window.addEventListener("popstate", res, { once: true }));
overlay.unmount();
await landed;
});
expect(new URLSearchParams(window.location.search).get("yt")).toBe("cats");
expect(nav.result.current.ytSearch).toBe("cats");
}, 30_000); // the provider's whole import graph loads inside the case (see the header)
});
@@ -17,6 +17,7 @@ import {
nextNavId,
notifyNav,
rememberNavPosition,
replaceView,
} from "../../lib/history";
import { foreignUrlKeys, moduleUrlKeys, pageTitleKey, reachablePage } from "./moduleRegistry";
import { CHANNEL_PAGE_KEYS } from "../../lib/channelPageUrlState";
@@ -86,7 +87,7 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
// The live YouTube search: named in the address (`yt`, and `ytn` for its count, lib/ytSearchUrlState)
// so a reload or a link opens it again; its own history entry, so Back steps player → search → feed.
// Whether it RUNS by itself is not the address's to say: `ytAsked` is the term this document was
// asked to search for (sent from the search box, or "Search YouTube again" pressed), on the entries
// asked to search for (sent from the search box, or "Search YouTube" pressed), on the entries
// it has stayed on since — leaving the search ends it. Anything else — a reload, a link, a Back or
// a Forward onto a search — runs only when it costs no quota (Feed decides).
const [ytSearch, setYtSearch] = useState<string | null>(() =>
@@ -136,7 +137,8 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
closeOverlaysThenNavigate(() => {
// A channel page overlays the content column, so a nav click must close it even when the
// underlying page is unchanged (e.g. "Feed" while a channel opened from the feed).
if (next === pageRef.current && !channelViewRef.current) {
// A live search on it is one too: the press opens the page's root, as over a channel.
if (next === pageRef.current && !channelViewRef.current && ytSearchRef.current == null) {
then?.();
return;
}
@@ -161,7 +163,7 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
notifyNav();
then?.();
}),
[pageRef, channelViewRef, endYtSearch],
[pageRef, channelViewRef, ytSearchRef, endYtSearch],
);
// A sub-view (channel / YT search) is an OVERLAY, not a page change. Like setPage it never lands
@@ -174,7 +176,7 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
const url = channelUrl(id);
if (window.history.state?._chan) {
const st = window.history.state;
window.history.replaceState({ ...st, _chan: id, _chanName: name ?? null }, "", url);
replaceView({ ...st, _chan: id, _chanName: name ?? null }, url);
} else {
const st = rememberNavPosition();
window.history.pushState({ ...st, _chan: id, _chanName: name ?? null }, "", url);
@@ -193,9 +195,8 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
// again: the channel's address carried none of it.
setChannelView(null);
const { _chan: _id, _chanName: _name, ...st } = window.history.state ?? {};
window.history.replaceState(
replaceView(
st,
"",
urlWithParams({
...closedChannelParams(),
...ytSearchParams(ytSearchRef.current, ytCountRef.current),
@@ -212,11 +213,7 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
if (st._yt || ytSearchFrom(here) != null) {
// Refine the search on screen, in place, at the count it shows (one a link opened too: it
// is the first entry of this document, so its new `_yt` mark has nothing of ours below it).
window.history.replaceState(
{ ...st, _yt: q },
"",
urlWithParams(ytSearchParams(q, ytCountFrom(here))),
);
replaceView({ ...st, _yt: q }, urlWithParams(ytSearchParams(q, ytCountFrom(here))));
} else {
// New sub-view entry, at the default count.
setYtCountState(DEFAULT_YT_COUNT);
@@ -235,9 +232,8 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
const setYtCount = useCallback(
(n: number) => {
setYtCountState(n);
window.history.replaceState(
window.history.state,
"",
replaceView(
window.history.state ?? {},
urlWithParams(ytSearchParams(ytSearchRef.current, n)),
);
},
@@ -251,7 +247,7 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
else {
endYtSearch();
const { _yt: _q, ...st } = window.history.state ?? {};
window.history.replaceState(st, "", urlWithParams(ytSearchParams(null, DEFAULT_YT_COUNT)));
replaceView(st, urlWithParams(ytSearchParams(null, DEFAULT_YT_COUNT)));
}
}, [endYtSearch]);
@@ -263,10 +259,7 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
const [pageSearchWasOn, setPageSearchWasOn] = useState(page);
if (pageSearchWasOn !== page) {
setPageSearchWasOn(page);
if (page !== "feed") {
setYtSearch(null);
setYtAsked(null);
}
if (page !== "feed") endYtSearch();
}
// The browser tab names the place and the object in it (DESIGN § Composition, "Where am I"):
@@ -349,8 +342,12 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
// The YouTube search is read from the address the browser restored, so Back/Forward opens or
// clears it to match the entry we landed on. One landed on without it has ended: a Forward back
// onto it is not asked for, and an API search waits for a press.
// A channel page opened from its results stands over it: its entry carries the search's mark
// (its address does not), and the search stays under it — closing a player over that channel
// lands there, and is no leaving of the search.
const here = new URLSearchParams(window.location.search);
const landed = p === "feed" ? ytSearchFrom(here) : null;
const under = e.state?._chan && typeof e.state._yt === "string" ? e.state._yt : null;
const landed = p === "feed" ? (ytSearchFrom(here) ?? under) : null;
setYtSearch(landed);
if (landed == null) setYtAsked(null);
setYtCountState(ytCountFrom(here));
@@ -227,6 +227,34 @@ describe("NavigationProvider · the YouTube search in the address", () => {
expect(search().get("yt")).toBeNull();
});
it("the Feed press on the search itself opens the plain feed, as over a channel", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
const depth = window.history.length;
act(() => result.current.setPage("feed"));
expect(result.current.ytSearch).toBeNull();
expect(search().get("yt")).toBeNull();
expect(window.history.length).toBe(depth + 1); // its own entry: Back returns to the search
});
it("a landing on a channel opened from the search (an overlay over it closing) keeps the search", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
act(() => result.current.openChannel("UC1"));
// A player over the channel closed: the step back lands on the channel's own entry.
act(() => {
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
});
expect(result.current.ytSearch).toBe("lofi");
expect(result.current.ytSearchAsked).toBe(true);
// Back off the channel: the search it stood over is still the one asked for.
window.history.replaceState({ sfPage: "feed", _yt: "lofi" }, "", "/?page=feed&yt=lofi");
act(() => {
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
});
expect(result.current.ytSearchAsked).toBe(true);
});
it("a channel closed in place over the search names the search again", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
@@ -39,7 +39,7 @@ export interface NavigationActions {
closeChannel: () => void;
enterYtSearch: (q: string) => void;
exitYtSearch: () => void;
/** Run the search on screen: the "Search YouTube again" press. */
/** Run the search on screen: the "Search YouTube" press. */
askYtSearch: () => void;
setYtCount: (n: number) => void;
}
@@ -83,6 +83,60 @@ describe("useOpenLinkedPlayer", () => {
expect(new URLSearchParams(window.location.search).has("watch")).toBe(false);
});
it("leaves a player opened while the row was on its way alone, and its address", async () => {
window.history.replaceState(null, "", "/?watch=Z");
let answer: (v: Video) => void = () => {};
vi.spyOn(api, "videoRow").mockReturnValue(new Promise((r) => (answer = r)));
const open = vi.fn();
renderHook(() => useOpenLinkedPlayer(true, () => undefined, open), { wrapper });
// A card clicked meanwhile: its player names itself in the address.
window.history.replaceState(null, "", "/?watch=Y");
answer(vid("Z"));
await new Promise((r) => setTimeout(r, 20));
expect(open).not.toHaveBeenCalled();
expect(new URLSearchParams(window.location.search).get("watch")).toBe("Y");
});
it("does not clear the address of a player opened since when its catalog read fails", async () => {
window.history.replaceState(null, "", "/?watch=Z");
let refuse: (e: Error) => void = () => {};
vi.spyOn(api, "videoRow").mockReturnValue(new Promise((_, r) => (refuse = r)));
renderHook(() => useOpenLinkedPlayer(true, () => undefined, vi.fn()), { wrapper });
window.history.replaceState(null, "", "/?watch=Y");
refuse(new Error("not found"));
await new Promise((r) => setTimeout(r, 20));
expect(new URLSearchParams(window.location.search).get("watch")).toBe("Y");
});
it("given up over a moved list, keeps the address of a player opened since", async () => {
window.history.replaceState(null, "", "/?watch=Z");
const { rerender } = renderHook(
({ scope }) => useOpenLinkedPlayer(false, () => undefined, vi.fn(), scope),
{ wrapper, initialProps: { scope: 1 } },
);
window.history.replaceState(null, "", "/?watch=Y");
rerender({ scope: 2 });
await new Promise((r) => setTimeout(r, 20));
expect(new URLSearchParams(window.location.search).get("watch")).toBe("Y");
});
it("stops looking once it opened: the video leaving the list asks the catalog for nothing", async () => {
window.history.replaceState(null, "", "/?watch=B");
const row = vi.spyOn(api, "videoRow").mockResolvedValue(vid("B"));
const find = vi.fn((id: string) => (id === "B" ? vid("B") : undefined));
const { rerender } = renderHook(
({ rows }) => useOpenLinkedPlayer(true, rows ? find : () => undefined, vi.fn()),
{ wrapper, initialProps: { rows: true } },
);
await waitFor(() => expect(find).toHaveBeenCalled());
find.mockClear();
rerender({ rows: false });
rerender({ rows: true });
await new Promise((r) => setTimeout(r, 20));
expect(find).not.toHaveBeenCalled();
expect(row).not.toHaveBeenCalled();
});
it("opens nothing, and asks for nothing, for an address that names no player", async () => {
window.history.replaceState(null, "", "/?q=talks");
const row = vi.spyOn(api, "videoRow");
@@ -14,7 +14,8 @@ import { notifyActionError } from "../../lib/actionErrors";
*
* `scope` names the list the address put it over (a playlist, a live search): when the host moves to
* another before it opened, the address under it named something else, and the player is given up —
* opened later, it would start over a list nobody linked, unasked. */
* opened later, it would start over a list nobody linked, unasked. So it is when a player opened
* meanwhile (a card clicked while the row was on its way): the address names that one now. */
export function useOpenLinkedPlayer(
ready: boolean,
find: (id: string) => Video | undefined,
@@ -24,14 +25,17 @@ export function useOpenLinkedPlayer(
const { t } = useTranslation();
const [linked] = useState(() => linkedPlayer()?.watch ?? null);
const [linkedScope] = useState(scope);
// Opened (or said to be gone) once; a ref, as nothing on screen reads it.
// Opened, said to be gone or given up, once. A ref for the effect (a StrictMode re-run of it must
// not open it twice); the state stops the lookup and the row fetch on screen after it.
const done = useRef(linked == null);
const [settled, setSettled] = useState(linked == null);
const moved = scope !== linkedScope;
const listed = ready && !moved && linked != null ? find(linked) : undefined;
const waiting = ready && !moved && !settled && linked != null;
const listed = waiting ? find(linked) : undefined;
const row = useQuery({
queryKey: qk.videoRow(linked ?? ""),
queryFn: () => api.videoRow(linked!),
enabled: ready && !moved && linked != null && !listed,
enabled: waiting && !listed,
retry: false,
});
const openIt = useEffectEvent(open);
@@ -41,12 +45,18 @@ export function useOpenLinkedPlayer(
});
useEffect(() => {
if (done.current) return;
if (moved) {
const settle = () => {
done.current = true;
// The address goes on naming it under the new list (a reload would open it there) — unless a
// player opened since names its own.
if (linkedPlayer()?.watch === linked) clearParams(...PLAYER_KEYS);
return;
// State, not derived: a one-way decision taken as the list or the row arrives. Derived from
// `listed`, the lookup and the row fetch would come back whenever the video left the list.
setSettled(true);
};
// A player opened since names its own: this one is not wanted any more.
if (linkedPlayer()?.watch !== linked) return settle();
if (moved) {
// The address goes on naming it under the new list (a reload would open it there).
clearParams(...PLAYER_KEYS);
return settle();
}
// 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
@@ -56,6 +66,6 @@ export function useOpenLinkedPlayer(
else if (row.data) openIt(row.data, false);
else if (row.isError) failed(row.error);
else return;
done.current = true;
settle();
}, [linked, moved, ready, listed, row.data, row.isError, row.error]);
}