fix(keys): epic-end review round 1 — Back, menus and dialogs keep the focus where it belongs

Deep-review of E11 (19 raised, 14 confirmed; 2 refuted, 3 latent test-hardening notes dropped).

- Back from a sub-view (a Plex show page, a Messages thread) restores the item it was opened from
  even when focus was still inside the view: the first attempt now waits one task, past the
  sub-view's own popstate listener (measured in Chrome: it left focus on <body>).
- The restore listener is installed at load, so the first Back after a reload finds it; a push
  cancels a restore still waiting for the last landing's lists.
- Navigating over an overlay asks it again, a render apart, while its entry stays: the Plex
  player peels one panel per Back step, so Shift+W over info + stats closed one panel and dropped
  the navigation.
- j/k: a native <button> item keeps its own Tab stop; landing twice on the same item no longer
  leaks its tabindex; after the focused item is removed (a hidden card) the next j goes on from
  its slot when that slot is on screen.
- An abandoned `g` no longer swallows a modifier chord (g, then Mod+K opened the browser search).
- A hover card above a dialog no longer switches its Tab trap off (player, Modal, wizard,
  Lightbox): new layerStack `anyBlockingLayerAbove`.
- "Manage views…" closes its menu before opening the dialog, through a shared `closeThenAct`
  that ActionMenu now uses too.
- Copy: the EN welcome says "Feed"; the EN unreachable reason no longer claims a change;
  stale comments about PlayerModal's scroll lock and dialog contract.
This commit is contained in:
2026-09-13 17:17:49 +02:00
parent bbd31c7143
commit f130a1c05a
22 changed files with 439 additions and 64 deletions
+30
View File
@@ -163,6 +163,36 @@ describe("closeOverlaysThenNavigate", () => {
}
});
// An overlay's Back callback is a Back STEP: the Plex player keeps its panels on one entry and peels
// one per call. Called once, the entry stayed and the navigation was dropped 1.5 s later — `i`, `d`,
// Shift+W in the player closed the info panel and nothing else (deep-review E11 round 1).
it("asks again, a render apart, when one call peels only a step off the overlay", async () => {
const back = stubBack();
try {
let steps = 2;
const calls: number[] = [];
const holder: { unmount?: () => void } = {};
const r = renderHook(() =>
useBackToClose(() => {
calls.push(steps);
if (--steps === 0) holder.unmount?.();
}),
);
holder.unmount = r.unmount;
await settle();
const navigate = vi.fn();
act(() => closeOverlaysThenNavigate(navigate));
expect(calls).toEqual([2]);
await act(async () => {
await new Promise((res) => setTimeout(res, 300));
});
expect(calls).toEqual([2, 1]); // never called again once the entry is gone
expect(navigate).toHaveBeenCalledTimes(1);
} finally {
back.mockRestore();
}
});
// The old helper ran after "a popstate" OR a 250 ms fallback, whichever came first — so a reclaim
// slower than the fallback undid the navigation. It must wait for the history, not the clock.
it("waits for a back() still in flight instead of pushing under it", async () => {
@@ -5,7 +5,7 @@
// stamped onto the entry being left (`rememberNavPosition`) and a popstate landing on it focuses the item
// once the page's lists are back. A landing is simulated the way the browser delivers one: the entry's
// state is current and a popstate carries it. Its own file: history.ts and listNav keep module state.
import { useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { afterEach, describe, expect, it } from "vitest";
import { act, cleanup, render, waitFor } from "@testing-library/react";
import { rememberNavPosition } from "./history";
@@ -92,6 +92,44 @@ describe("rememberNavPosition · Back focuses the item a view was left from", ()
await waitFor(() => expect(focused()).toBe("a1"));
});
// A sub-view (a Plex show page) switches back in its OWN popstate listener, registered after this
// module's: while ours runs, focus still sits in the view being left. Measured in Chrome (deep-review
// E11 round 1) — Discover card → show → `j` on the show page → Back left focus on <body>.
it("restores when a later popstate listener switches the view the focus was still in", async () => {
const { unmount } = render(<Page />);
const stamped = leaveFrom("b1", 4);
unmount();
function Views() {
const [view, setView] = useState<"sub" | "page">("sub");
useEffect(() => {
const onPop = () => setView("page");
window.addEventListener("popstate", onPop);
return () => window.removeEventListener("popstate", onPop);
}, []);
return view === "page" ? <Page /> : <List id="s" count={2} />;
}
render(<Views />);
press("j");
expect(focused()).toBe("s0");
landOn(stamped);
await waitFor(() => expect(focused()).toBe("b1"));
});
// A restore still waiting for the landed page's lists must not outlive the next push: it would
// focus "list 1, item 1" of whatever page that push opened.
it("is cancelled by the next push", async () => {
const { unmount } = render(<Page />);
const stamped = leaveFrom("b1", 4);
unmount();
landOn(stamped);
render(<List id="b" count={3} />); // one list of the two: the restore keeps waiting
await sleep(120);
window.history.pushState({ ...rememberNavPosition(), view: "elsewhere" }, "");
render(<Page />); // enough lists now, on the page the push opened
await sleep(150);
expect(focused()).toBeUndefined();
});
it("leaves focus where it is when something already has it", async () => {
const { unmount } = render(<Page />);
const stamped = leaveFrom("b1", 4);
@@ -0,0 +1,50 @@
// @vitest-environment jsdom
//
// The stamp `rememberNavPosition` leaves in history.state survives a reload, but module state does not:
// the listener that reads it was installed by the first push, so after F5 the first Back onto a
// stamped entry restored nothing (deep-review E11 round 1). Its own file, because the point is a
// module that has made NO push yet — any other test in history.navPosition would have made one.
import { useRef } from "react";
import { afterEach, expect, it } from "vitest";
import { act, cleanup, render, waitFor } from "@testing-library/react";
import "./history";
import { navItemAttrs, useListNav } from "./listNav";
function List({ id, count }: { id: string; count: number }) {
const ref = useRef<HTMLDivElement>(null);
useListNav(ref, { enabled: true });
return (
<div ref={ref}>
{Array.from({ length: count }, (_, i) => (
<div key={i} data-testid={`${id}${i}`} {...navItemAttrs(i)}>
{id}
{i}
</div>
))}
</div>
);
}
afterEach(() => {
cleanup();
window.history.replaceState(null, "");
});
it("restores on a landing before this load has pushed anything", async () => {
// An entry stamped before the reload: list 1 of 2, item 1.
const state = { sfPage: "home", sfNav: { list: 1, lists: 2, index: 1 } };
window.history.replaceState(state, "");
render(
<>
<List id="a" count={2} />
<List id="b" count={3} />
</>,
);
act(() => {
window.dispatchEvent(new PopStateEvent("popstate", { state }));
});
await waitFor(() =>
expect((document.activeElement as HTMLElement | null)?.dataset.testid).toBe("b1"),
);
expect(window.history.state.sfNav).toBeUndefined();
});
+29 -7
View File
@@ -69,11 +69,10 @@ export function subscribeNav(cb: () => void): () => void {
// See lib/listNav "The item a view was left from". Stamped onto the entry being LEFT, right before a
// push opens a new view over it; read when Back/Forward lands on that entry, and dropped from it there,
// so a later landing on the same entry — an overlay closing over it — cannot pull focus to an old item.
// Installed at load, not by the first push: a stamp survives a reload in history.state, and the first
// Back after one must still find a listener (deep-review E11 round 1).
let cancelNavRestore = () => {};
let navRestoreInstalled = false;
function ensureNavRestore(): void {
if (navRestoreInstalled) return;
navRestoreInstalled = true;
if (typeof window !== "undefined") {
window.addEventListener("popstate", (e) => {
cancelNavRestore();
const pos = (e.state as { sfNav?: NavPosition } | null)?.sfNav;
@@ -88,7 +87,9 @@ function ensureNavRestore(): void {
* channel, a tab). Returns the current state WITHOUT the stamp: a push that spreads the current state
* must spread this, so the new entry does not inherit a position it was never left from. */
export function rememberNavPosition(): Record<string, unknown> {
ensureNavRestore();
// A restore still waiting for the last landing's lists belongs to the page being left: left
// running, it would focus "list N, item M" of whatever page this push opens.
cancelNavRestore();
const { sfNav: _stale, ...st } = (window.history.state ?? {}) as Record<string, unknown>;
const pos = navPosition();
window.history.replaceState(pos ? { ...st, sfNav: pos } : st, "");
@@ -251,6 +252,11 @@ function historyInSync(): boolean {
// render (measured back()→popstate: 1–13 ms in Chrome); nothing in the app refuses a close today,
// but a future "discard your changes?" guard must not be navigated out from under.
const CLOSE_TIMEOUT_MS = 1500;
// An overlay's Back callback is a Back STEP, and one entry can hold several steps: the Plex player's
// panels share a single entry and Back peels one per press. Navigating over it asks again, a render
// apart (the callback reads what the last one closed), until the entry is gone or the timeout drops
// the command.
const RECLOSE_MS = 50;
/** Close `targets` (via `close`), then `run` once they have unmounted AND the history has caught up.
*
@@ -267,7 +273,12 @@ const CLOSE_TIMEOUT_MS = 1500;
* `run` goes out on a fresh task, never inside the popstate dispatch that settled it: listeners
* registered before ours (NavigationProvider's) have read that event already, but ones after it
* have not, and a page applied from the OLD entry after our push would undo the navigation. */
function afterClosing(targets: readonly Overlay[], close: () => void, run: () => void): void {
function afterClosing(
targets: readonly Overlay[],
close: () => void,
run: () => void,
reclose = false,
): void {
let done = false;
let queued = false;
const gone = () => targets.every((o) => !overlayStack.includes(o));
@@ -277,7 +288,13 @@ function afterClosing(targets: readonly Overlay[], close: () => void, run: () =>
syncWaiters.delete(check);
window.removeEventListener("popstate", check);
clearTimeout(timeout);
clearInterval(again);
};
const again = reclose
? setInterval(() => {
if (!done && !gone()) close();
}, RECLOSE_MS)
: undefined;
function check(): void {
if (queued || !ready()) return;
queued = true;
@@ -318,7 +335,12 @@ export function closeOverlaysThenNavigate(navigate: () => void): void {
return;
}
const targets = [...overlayStack];
afterClosing(targets, () => [...targets].reverse().forEach((o) => o.cb()), navigate);
const close = () =>
[...targets]
.reverse()
.filter((o) => overlayStack.includes(o))
.forEach((o) => o.cb());
afterClosing(targets, close, navigate, true);
}
/** Close the overlay a control lives in, then run its command once that overlay's entry is back —
+16
View File
@@ -87,6 +87,22 @@ describe("two-step sequences", () => {
expect(calls).toEqual(["goDownloads"]);
});
// No second step needs a modifier (D1), so a chord with one is the reader changing their mind: it
// must reach its own row. Swallowed, `g` then Ctrl+K opened the browser's search, not the palette.
it("lets a modifier chord abandon the sequence and match as itself", () => {
const calls: string[] = [];
const global = {
help: () => calls.push("help"),
palette: () => calls.push("palette"),
home: () => calls.push("home"),
};
dispatch(press({ key: "g" }), "page", pageHandlers(calls));
const k = press({ key: "k", ctrlKey: true, metaKey: true });
expect(dispatch(k, "global", global)).toBe(true);
expect(dispatch(press({ key: "f" }), "page", pageHandlers(calls))).toBe(false); // not `g f`
expect(calls).toEqual(["palette"]);
});
it("does not start or finish inside a text field", () => {
const calls: string[] = [];
const input = document.createElement("input");
+8 -1
View File
@@ -297,7 +297,14 @@ function liveSequence(e: KeyboardEvent): typeof pending {
pending = null;
return null;
}
return MODIFIER_KEYS.has(e.key) ? null : pending;
if (MODIFIER_KEYS.has(e.key)) return null;
// A chord with a modifier cannot be a second step (no binding may need one, D1): it abandons the
// sequence and is matched as itself, or `g` then Mod+K would open the browser's search, not ours.
if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) {
pending = null;
return null;
}
return pending;
}
const stepsOf = (chord: string): string[] => chord.split(" ");
+10 -1
View File
@@ -51,6 +51,14 @@ export function anyLayerAbove(id: number): boolean {
return i !== -1 && i < stack.length - 1;
}
/** True when a layer that owns the keyboard sits above `id` — the predicate for a dialog's Tab trap.
* A tooltip or hover card open under a resting pointer takes Escape first, but not the Tab: deferring
* the trap to it let Shift+Tab walk out of the dialog into the page behind its scrim. */
export function anyBlockingLayerAbove(id: number): boolean {
const i = stack.indexOf(id);
return i !== -1 && stack.slice(i + 1).some((x) => !passive.has(x));
}
// UX-8 — a layer that ACTS on an Escape stamps the event here; a lower layer with its own key handler
// (the players, listening on `window`) reads the stamp instead of re-reading the stack. This closes
// the "one Escape closes BOTH the popover and the player" bug: the popover's Escape listener is on
@@ -76,7 +84,7 @@ export function useLayer(
active: boolean,
onEscape?: () => void,
opts?: { passive?: boolean },
): { isTopmost: () => boolean; anyAbove: () => boolean } {
): { isTopmost: () => boolean; anyAbove: () => boolean; blockingAbove: () => boolean } {
const idRef = useRef<number | null>(null);
const escRef = useRef(onEscape);
escRef.current = onEscape;
@@ -110,5 +118,6 @@ export function useLayer(
return {
isTopmost: () => idRef.current != null && isTopmost(idRef.current),
anyAbove: () => idRef.current != null && anyLayerAbove(idRef.current),
blockingAbove: () => idRef.current != null && anyBlockingLayerAbove(idRef.current),
};
}
+82 -2
View File
@@ -3,9 +3,9 @@
// `lib/listNav` against real DOM: `j`/`k` from item to item and across lists in reading order, the
// arrows around a grid, Enter as a click on the item's own "open" element — and the places where the
// keys must stay out of the way (a field, an overlay, a control inside the card).
import { useRef } from "react";
import { useRef, useState } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { navItemAttrs, useListNav } from "./listNav";
import { pushLayer, removeLayer } from "./layerStack";
@@ -349,3 +349,83 @@ describe("useListNav · keys and lists it must leave alone", () => {
expect(focused()).toBe("a1");
});
});
describe("useListNav · the roving tabindex and a removed item (deep-review E11 round 1)", () => {
// A tile that is a native <button> is a Tab stop already. A tabindex="-1" on it took it out of the
// Tab order until the next `j` moved elsewhere: Shift+Tab back to a genre tile skipped it.
it("leaves an item that is a Tab stop in its own right out of the tabindex it roves", () => {
function Tiles() {
const ref = useRef<HTMLDivElement>(null);
useListNav(ref, { enabled: true });
return (
<div ref={ref}>
{[0, 1].map((i) => (
<button key={i} type="button" {...navItemAttrs(i)} data-testid={`t${i}`}>
tile
</button>
))}
</div>
);
}
render(<Tiles />);
press("j");
expect(focused()).toBe("t0");
expect(screen.getByTestId("t0").hasAttribute("tabindex")).toBe(false);
press("j");
expect(focused()).toBe("t1");
expect(screen.getByTestId("t1").hasAttribute("tabindex")).toBe(false);
});
// Landing again on the item that already holds the roved tabindex (focus went to <body> in between)
// forgot it, so it kept tabindex="-1" for good — and a click on its blank area focused the card.
it("gives the tabindex back after landing twice on the same item", () => {
render(<List id="a" count={3} />);
press("j");
expect(focused()).toBe("a0");
act(() => (document.activeElement as HTMLElement).blur());
press("j");
expect(focused()).toBe("a0");
press("j");
expect(focused()).toBe("a1");
expect(screen.getByTestId("a0").hasAttribute("tabindex")).toBe(false);
});
// Hiding the focused feed card unmounts it and drops focus to <body>; the next `j` started over at
// the first visible card instead of going on from the hidden card's slot.
it("goes on from the slot of an item that was removed under the focus", () => {
function Removable() {
const [ids, setIds] = useState([0, 1, 2, 3]);
const ref = useRef<HTMLDivElement>(null);
useListNav(ref, { enabled: true });
return (
<div ref={ref}>
{ids.map((id, i) => (
<div key={id} {...navItemAttrs(i)} data-testid={`r${id}`}>
<button
data-testid={`r${id}-hide`}
onClick={() => setIds((xs) => xs.filter((x) => x !== id))}
>
hide
</button>
</div>
))}
</div>
);
}
withLayout(
(_, n) => ({ left: 0, top: n * 100 }),
() => {
render(<Removable />);
press("j");
press("j");
press("j");
expect(focused()).toBe("r2");
act(() => screen.getByTestId("r2-hide").focus());
fireEvent.click(screen.getByTestId("r2-hide"));
expect(document.activeElement).toBe(document.body);
press("j");
expect(focused()).toBe("r3");
},
);
});
});
+51 -10
View File
@@ -120,13 +120,44 @@ function firstVisible(): { list: NavList; index: number } | null {
return fallback;
}
/** The item focus was last inside, so a `j` after that item was REMOVED (a feed card hidden, a
* download deleted — focus falls to <body>) goes on from its slot instead of starting over. */
let last: { list: NavList; index: number; el: HTMLElement } | null = null;
function onFocusIn(e: FocusEvent): void {
const item = (e.target as HTMLElement | null)?.closest?.<HTMLElement>(`[${INDEX}]`);
const list =
item && lists.get(item.parentElement?.closest<HTMLElement>(`[${LIST}]`) as HTMLElement);
if (item && list) last = { list, index: indexOf(item), el: item };
}
/** Where `j` (`k`: the item before) lands after the last-focused item left the DOM: the item now in
* its slot, if that slot is on screen. An item that only scrolled out of a virtualized list has left
* the DOM too, but its slot is off screen then, so the reader's viewport (`firstVisible`) wins. */
function slotOfRemoved(delta: 1 | -1): { list: NavList; index: number } | null {
if (!last || last.el.isConnected || lists.get(last.list.el) !== last.list) return null;
const n = last.list.count();
const index = Math.min(Math.max(0, delta > 0 ? last.index : last.index - 1), n - 1);
const el = index >= 0 ? itemAt(last.list, index) : null;
if (!el) return null;
const box = scrollParent(last.list.el)?.getBoundingClientRect();
const r = el.getBoundingClientRect();
const band = (box?.top ?? 0) + (parseFloat(getComputedStyle(el).scrollMarginTop) || 0);
return r.bottom > band && r.top < (box?.bottom ?? window.innerHeight)
? { list: last.list, index }
: null;
}
function focusItem(el: HTMLElement, reveal = true): void {
if (roved && roved !== el) roved.removeAttribute("tabindex");
roved = null;
// An item that is focusable in its own right (a Plex card is a role=button) keeps its tabindex.
if (!el.hasAttribute("tabindex")) {
el.setAttribute("tabindex", "-1");
roved = el;
if (roved !== el) {
roved?.removeAttribute("tabindex");
roved = null;
// An item that is a Tab stop in its own right (a native <button> tile, a role=button card with
// tabIndex 0) keeps it: a -1 here would take it out of the Tab order.
if (!el.hasAttribute("tabindex") && el.tabIndex < 0) {
el.setAttribute("tabindex", "-1");
roved = el;
}
}
el.focus({ preventScroll: true });
// `nearest` + the item's scroll margins: a visible item does not move, an item under the floating
@@ -151,7 +182,7 @@ function focusIndex(list: NavList, index: number): void {
function step(delta: 1 | -1): void {
const cur = current();
if (!cur) {
const start = firstVisible();
const start = slotOfRemoved(delta) ?? firstVisible();
if (start) focusIndex(start.list, start.index);
return;
}
@@ -284,7 +315,11 @@ export function restoreNavPosition(pos: NavPosition): () => void {
if (el) return focusItem(el, false);
if (Date.now() < deadline) timer = setTimeout(attempt, RESTORE_POLL_MS);
};
attempt();
// Not inside the popstate dispatch that landed: a sub-view's own listener (`useHistorySubview`)
// may run after ours and has not switched the view yet — focus still sits in the view being left,
// and "focus is already somewhere" would give up for good (measured in Chrome, deep-review E11
// round 1: Plex show → Back left focus on <body>). One task later the view has rendered.
timer = setTimeout(attempt, 0);
return () => clearTimeout(timer);
}
@@ -309,11 +344,17 @@ export function useListNav(
reveal: (i) => optsRef.current.reveal?.(i),
});
el.setAttribute(LIST, "");
if (lists.size === 1) window.addEventListener("keydown", onKey);
if (lists.size === 1) {
window.addEventListener("keydown", onKey);
document.addEventListener("focusin", onFocusIn);
}
return () => {
lists.delete(el);
el.removeAttribute(LIST);
if (lists.size === 0) window.removeEventListener("keydown", onKey);
if (lists.size === 0) {
window.removeEventListener("keydown", onKey);
document.removeEventListener("focusin", onFocusIn);
}
};
}, [ref, opts.enabled]);
}